Swift 语言基础:iOS 与 macOS 开发入门
Swift 语言基础:iOS 与 macOS 开发入门
Swift 是 Apple 推出的强类型、编译式编程语言,用于构建 iOS、macOS、watchOS 和 tvOS 应用。它兼具现代语言的表达能力与高性能,是进入 Apple 开发生态的首选语言。本教程将从零开始,带你掌握 Swift 的基本语法与核心概念,为后续的 App 开发打下扎实基础。
环境准备:无需 Mac 也能写 Swift
在 Mac 上,推荐使用 Xcode(从 Mac App Store 免费下载)。Xcode 集成了编辑器、编译器和模拟器,新建 Playground 即可快速试验代码。如果你使用 Windows 或 Linux,可使用 Swift 官方工具链 搭配 VS Code 插件,或通过在线 Swift Playground(如 SwiftFiddle)直接运行代码。
变量与常量:用 var 和 let 声明数据
Swift 鼓励使用不可变数据提升代码安全性。声明常量用 let,变量用 var。
let maxRetryCount = 3 // 常量,不可更改
var currentRetry = 0 // 变量,可被修改
currentRetry += 1
Swift 通过类型推断自动识别类型,也可显式标注类型:
var welcomeMessage: String = "Hello, Swift"
基本数据类型与转换
Swift 提供核心类型:Int、Double、Float、Bool、String。它们之间没有自动转换,需明确写出。
let score = 95
let pi = 3.14159
let isPassed = true
let name = "Taylor"
let sum = Double(score) + pi // 显式转换
字符串插值是输出常用形式:
let age = 25
let message = "I am \(age) years old."
集合类型:数组与字典
数组存放有序、可重复的值;字典存放键值对,数据无序。
// 数组
var fruits = ["Apple", "Banana", "Cherry"]
fruits.append("Durian")
let firstFruit = fruits[0]
// 字典
var occupations = ["Malcolm": "Captain", "Kaylee": "Mechanic"]
occupations["Jayne"] = "Public Relations"
使用类型标注创建空集合:
var emptyArray: [Int] = []
var emptyDict: [String: Double] = [:]
控制流:条件与循环
条件语句 使用 if、else if 和 else,条件表达式必须是布尔类型。
let temperature = 30
if temperature > 35 {
print("It's hot.")
} else if temperature > 20 {
print("It's moderate.")
} else {
print("It's cold.")
}
可选绑定 结合 if let 安全解包可选值(见下文可选类型)。
循环 有 for-in、while 和 repeat-while。
// 遍历数组
for fruit in fruits {
print(fruit)
}
// 遍历范围
for index in 1...5 {
print(index)
}
// while 循环
var countdown = 3
while countdown > 0 {
print(countdown)
countdown -= 1
}
switch 支持任意类型和复杂匹配,默认不需要写 break。
let someCharacter: Character = "z"
switch someCharacter {
case "a", "A":
print("The letter A")
case "z":
print("The letter Z")
default:
print("Some other character")
}
函数:封装可复用的代码块
使用 func 定义函数,参数需指定类型,返回值用 -> 声明。
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!"
return greeting
}
print(greet(person: "Anna"))
无返回值 时省略 -> 或返回 Void。函数支持内部和外部参数名,外部参数名提高调用可读性。
func divide(_ dividend: Double, by divisor: Double) -> Double {
return dividend / divisor
}
let result = divide(10.0, by: 2.0) // 调用时忽略第一个标签
可选类型:处理值缺失的安全机制
Swift 用 Optional 表示一个值可能存在也可能为 nil。在类型后加 ? 声明可选类型。
var serverResponseCode: Int? = 404
serverResponseCode = nil // 现在不包含值
强制解包 使用 ! 获取值,但如果原值为 nil 会引发运行时错误,因此更推荐安全解包。
if let code = serverResponseCode {
print("Response code: \(code)")
} else {
print("No response code")
}
还可用空合运算符 ?? 提供默认值:
let finalCode = serverResponseCode ?? 500
类与结构体:面向对象编程的基础
类 (class) 和结构体 (struct) 都能定义属性和方法,主要区别:类是引用类型,结构体是值类型。
// 结构体
struct Point {
var x = 0.0, y = 0.0
func description() -> String {
return "(\(x), \(y))"
}
}
// 类
class Shape {
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape named \(name)"
}
}
实例化时结构体自动获得成员初始化器;类必须定义 init。Swift 常用结构体(如 String、Array),因为它们更轻量且安全。
扩展与协议:增强类型功能
扩展 为已有类型添加新方法,但不能添加存储属性。
extension Double {
var km: Double { return self * 1000.0 }
}
let marathon = 42.km
协议 定义方法、属性的蓝图,相当于其他语言的接口。类、结构体、枚举都可以遵循协议。
protocol Identifiable {
var id: String { get }
func identify() -> String
}
struct User: Identifiable {
var id: String
func identify() -> String {
return "User ID: \(id)"
}
}
错误处理:优雅应对异常
采用 do-catch 语句与 throw 关键字。
enum FileError: Error {
case fileNotFound
}
func readFile(name: String) throws -> String {
throw FileError.fileNotFound
}
do {
let content = try readFile(name: "data.txt")
print(content)
} catch FileError.fileNotFound {
print("File not found.")
} catch {
print("Unexpected error.")
}
下一步:构建你的第一个 iOS 应用
掌握以上基础后,你已经具备了读懂大多数 Swift 代码的能力。接下来可探索:
- 使用 SwiftUI 或 UIKit 构建界面
- 结合 Xcode 的 Interface Builder 拖拽布局
- 学习 GCD 或 async/await 处理异步任务
Swift 的学习路径平滑且现代,从基础语法到多平台开发,Apple 的官方文档(Swift Programming Language)始终是最好的参考。let’s swift!