Z
ZHANK
编程在线教程Swift 教程Hello World 与程序结构
入门基础

Hello World 与程序结构

print 输出、注释、语句不需要分号、Playground 即时反馈

Hello World 与程序结构

Swift 程序没有 main 函数——入口是文件顶层代码。语句不需要分号(但写了也行)。

学完本章你将: 掌握 print、注释、Playground 即时反馈。


Hello World

swift
print("Hello, Swift!")
print("你好,世界!")

// print 支持字符串插值
let name = "小明"
print("我叫\(name)")

// 多参数
print("A", "B", "C", separator: "-")  // A-B-C

程序结构

swift
// Swift 文件顶层就是入口——不需要 main()
// 如果需要,可以用 @main

// 注释
// 单行注释

/*
    多行注释
    /* 嵌套注释——Swift 支持! */
*/

// MARK: - 标记(Xcode 中显示在导航栏)
// TODO: 待完成
// FIXME: 需要修复

Playground 特色

swift
// Playground 中每行代码右侧即时显示结果
let x = 42           // 42
let y = x * 2        // 84

// 可以嵌入 UI 预览
import PlaygroundSupport
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .blue
PlaygroundPage.current.liveView = view