Swift 基础语法详细解析
Swift 是 Apple 于 2014 年推出的现代编程语言,用于开发 iOS、macOS、watchOS、tvOS 以及 Linux 和 Windows 平台的应用。它结合了 C 和 Objective-C 的性能,同时融入了现代编程语言的简洁性和安全性。以下从基础到核心特性全面介绍 Swift 语法。
一、基本特性与开发环境
1. 主要特点
- 类型安全:编译器会检查类型匹配,避免类型错误
- 类型推断:无需显式声明变量类型,编译器可自动推断
- 简洁代码:相比 Objective-C 大幅减少模板代码
- 安全机制 :默认禁止空指针(
nil
),减少运行时崩溃 - 函数式编程:支持闭包、高阶函数等函数式特性
- 与 Objective-C 兼容:可在同一项目中混合使用
2. 开发环境
- 主要使用 Xcode(Apple 官方 IDE)
- 也可使用 VS Code 配合 Swift 插件在其他平台开发
二、基本语法结构
1. 程序入口
Swift 程序不需要 main
函数,默认从代码最顶层开始执行:
swift
print("Hello, Swift!") // 这就是一个完整的 Swift 程序
2. 变量与常量
声明方式
- 常量 :使用
let
声明,值一旦设定就不能改变 - 变量 :使用
var
声明,值可以随时修改
swift
let maximumNumberOfLoginAttempts = 10 // 常量
var currentLoginAttempt = 0 // 变量
// 变量可以修改
currentLoginAttempt += 1
// 常量不能修改(会编译错误)
// maximumNumberOfLoginAttempts = 11
类型标注
Swift 通常会自动推断类型,但也可以显式指定:
swift
let pi: Double = 3.14159
var welcomeMessage: String = "Hello"
var score: Int = 100
3. 基本数据类型
数值类型
- 整数:
Int
(默认,根据平台自动为 32/64 位)、Int8
、Int16
、Int32
、Int64
- 无符号整数:
UInt
、UInt8
等(不推荐,可能导致溢出问题) - 浮点数:
Double
(64 位,精度高)、Float
(32 位)
swift
let integerValue = 42 // Int
let doubleValue = 3.14 // Double
let floatValue: Float = 2.718 // 需要显式标注
布尔类型
Bool
类型只有两个可能的值:true
和 false
swift
let isSwiftFun: Bool = true
let isFishFlying: Bool = false
字符串类型
String
表示文本序列,使用双引号 "
包裹
swift
let greeting = "Hello, Swift"
let emptyString = "" // 空字符串
let anotherEmptyString = String() // 另一种创建空字符串的方式
// 字符串拼接
let firstName = "John"
let lastName = "Doe"
let fullName = firstName + " " + lastName // "John Doe"
// 字符串插值
let age = 30
let introduction = "I'm \(age) years old" // "I'm 30 years old"
元组(Tuple)
元组可以将多个值组合成一个复合值,值可以是不同类型
swift
let httpStatus = (404, "Not Found") // (Int, String) 类型的元组
// 访问元组元素
print("Status code: \(httpStatus.0)") // 404
print("Message: \(httpStatus.1)") // Not Found
// 给元组元素命名
let response = (statusCode: 200, message: "OK")
print("Status: \(response.statusCode)") // 200
4. 可选类型(Optionals)
Swift 中默认不允许变量为 nil
,可选类型用于表示一个值可能存在或不存在的情况,通过在类型后加 ?
表示。
基本用法
swift
var optionalString: String? = "Hello" // 可以为 nil 的 String
optionalString = nil // 合法
var nonOptionalString: String = "Hello" // 不可以为 nil
// nonOptionalString = nil // 编译错误
解包可选类型
使用 !
强制解包(已知可选类型有值时):
swift
let possibleNumber: String? = "123"
let convertedNumber = Int(possibleNumber!) // 强制解包,如果 possibleNumber 是 nil 会崩溃
更安全的方式是使用可选绑定:
swift
if let actualNumber = Int(possibleNumber) {
print("The string has a number value of \(actualNumber)")
} else {
print("The string could not be converted to a number")
}
隐式解包可选类型
通过 !
声明,首次赋值后可像非可选类型一样使用(但仍可能为 nil):
swift
let assumedString: String! = "An implicitly unwrapped optional string"
let implicitString: String = assumedString // 无需解包
三、控制流
1. 条件语句
if 语句
swift
let temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
} else {
print("It's not that cold. Wear a light jacket.")
}
switch 语句
Swift 的 switch 比 C 语言更强大,支持多种类型匹配:
swift
let someCharacter: Character = "z"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
// 区间匹配
let approximateCount = 62
switch approximateCount {
case 0:
print("No items")
case 1..<5:
print("A few items")
case 5..<12:
print("Several items")
case 12..<100:
print("Dozens of items")
default:
print("Many items")
}
2. 循环语句
for-in 循环
用于遍历序列(数组、范围、字符串等):
swift
// 遍历范围
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 遍历数组
let animals = ["cat", "dog", "bird"]
for animal in animals {
print(animal)
}
// 遍历字典
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animal, legs) in numberOfLegs {
print("\(animal)s have \(legs) legs")
}
while 循环
swift
var count = 0
while count < 5 {
print(count)
count += 1
}
// repeat-while(相当于 do-while)
var anotherCount = 0
repeat {
print(anotherCount)
anotherCount += 1
} while anotherCount < 5
四、集合类型
1. 数组(Array)
有序集合,存储相同类型的值
swift
// 创建数组
var shoppingList: [String] = ["Eggs", "Milk"]
// 类型推断
var fruits = ["Apple", "Banana", "Orange"]
// 添加元素
shoppingList.append("Flour")
shoppingList += ["Baking Powder"]
// 访问元素
print(shoppingList[0]) // "Eggs"
// 修改元素
shoppingList[0] = "Organic Eggs"
// 插入元素
shoppingList.insert("Maple Syrup", at: 0)
// 删除元素
let removedItem = shoppingList.remove(at: 0)
// 遍历数组
for item in shoppingList {
print(item)
}
2. 字典(Dictionary)
无序的键值对集合
swift
// 创建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
// 简化创建(类型推断)
var heights = ["Yao Ming": 226, "Kobe Bryant": 198]
// 添加键值对
airports["LHR"] = "London Heathrow"
// 修改值
airports["YYZ"] = "Toronto International"
// 访问值
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName)")
} else {
print("That airport is not in the dictionary.")
}
// 删除键值对
airports["APL"] = nil
// 遍历字典
for (code, name) in airports {
print("\(code): \(name)")
}
3. 集合(Set)
无序的唯一值集合
swift
// 创建集合
var letters = Set<Character>()
letters.insert("a")
// 简化创建
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// 插入元素
favoriteGenres.insert("Jazz")
// 检查是否包含元素
if favoriteGenres.contains("Rock") {
print("I like rock music")
}
// 删除元素
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre) was removed")
}
// 遍历集合
for genre in favoriteGenres {
print(genre)
}
五、函数
函数是执行特定任务的代码块,使用 func
关键字定义。
1. 基本函数
swift
// 无参数无返回值
func greet() {
print("Hello!")
}
greet()
// 有参数无返回值
func greet(person: String) {
print("Hello, \(person)!")
}
greet(person: "Bob")
// 有参数有返回值
func add(a: Int, b: Int) -> Int {
return a + b
}
let sum = add(a: 3, b: 5) // 8
2. 函数参数标签和参数名
可以指定参数标签,使函数调用更具可读性:
swift
func greet(person: String, from hometown: String) -> String {
return "Hello \(person)! Glad you could visit from \(hometown)."
}
print(greet(person: "Bill", from: "Cupertino")) // "Hello Bill! Glad you could visit from Cupertino."
使用 _
可以省略参数标签:
swift
func multiply(_ a: Int, _ b: Int) -> Int {
return a * b
}
let product = multiply(4, 5) // 20
3. 默认参数值
swift
func greet(person: String, greeting: String = "Hello") {
print("\(greeting), \(person)!")
}
greet(person: "Alice") // "Hello, Alice!"
greet(person: "Bob", greeting: "Hi") // "Hi, Bob!"
4. 可变参数
接受零个或多个特定类型的参数:
swift
func sumOf(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
sumOf() // 0
sumOf(numbers: 1, 2, 3, 4) // 10
5. 函数类型
函数可以作为参数或返回值:
swift
// 函数类型为 (Int, Int) -> Int
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
// 将函数作为参数
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5) // "Result: 8"
// 函数作为返回值
func stepForward(_ input: Int) -> Int {
return input + 1
}
func stepBackward(_ input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (Int) -> Int {
return backward ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
currentValue = moveNearerToZero(currentValue) // 2
六、闭包
闭包是自包含的函数代码块,可以在代码中传递和使用,类似于其他语言中的匿名函数或 lambda 表达式。
1. 基本语法
swift
// 完整格式
let closure = { (parameters) -> returnType in
statements
}
// 示例:计算两个数的和
let addClosure = { (a: Int, b: Int) -> Int in
return a + b
}
let result = addClosure(2, 3) // 5
2. 简化闭包
Swift 提供了多种闭包简化方式:
swift
// 原函数
func calculate(_ a: Int, _ b: Int, using function: (Int, Int) -> Int) -> Int {
return function(a, b)
}
// 完整闭包调用
let result1 = calculate(10, 5, using: { (a: Int, b: Int) -> Int in
return a - b
})
// 简化1:类型推断
let result2 = calculate(10, 5, using: { a, b in
return a - b
})
// 简化2:隐式返回(单表达式)
let result3 = calculate(10, 5, using: { a, b in a - b })
// 简化3:参数名称缩写($0, $1, ...)
let result4 = calculate(10, 5, using: { $0 - $1 })
// 简化4:尾随闭包(当闭包是最后一个参数时)
let result5 = calculate(10, 5) { $0 - $1 }
3. 捕获值
闭包可以捕获和存储其所在上下文中任意常量和变量的引用:
swift
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
let incrementByTen = makeIncrementer(forIncrement: 10)
print(incrementByTen()) // 10
print(incrementByTen()) // 20
七、结构体和类
结构体(struct
)和类(class
)是构建复杂数据类型的基础,都可以定义属性和方法。
1. 结构体
值类型,赋值或传递时会被复制:
swift
struct Resolution {
var width = 0
var height = 0
}
// 创建实例
let resolution = Resolution()
print("Resolution: \(resolution.width) x \(resolution.height)") // 0 x 0
var hd = Resolution(width: 1920, height: 1080)
var cinema = hd // 结构体是值类型,cinema 是 hd 的副本
cinema.width = 2048
print("hd width: \(hd.width)") // 1920(hd 不受 cinema 修改影响)
2. 类
引用类型,赋值或传递时传递的是引用:
swift
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
// 创建实例
let videoMode = VideoMode()
videoMode.resolution.width = 1280
videoMode.interlaced = true
videoMode.name = "1080i"
videoMode.frameRate = 29.97
let anotherVideoMode = videoMode // 类是引用类型,anotherVideoMode 和 videoMode 引用同一个实例
anotherVideoMode.frameRate = 30.0
print("videoMode frameRate: \(videoMode.frameRate)") // 30.0(被 anotherVideoMode 修改)
3. 结构体与类的主要区别
- 结构体是值类型,类是引用类型
- 结构体默认有成员初始化器,类需要自己定义
- 结构体不能继承,类可以继承
- 结构体不能被 deinitialized,类可以
八、属性
属性是与结构体、类和枚举关联的值。
1. 存储属性
存储常量或变量作为实例的一部分:
swift
struct FixedLengthRange {
var firstValue: Int
let length: Int
}
var range = FixedLengthRange(firstValue: 0, length: 3)
range.firstValue = 10 // 变量属性可以修改
// range.length = 4 // 常量属性不能修改
2. 计算属性
不直接存储值,而是提供一个 getter 和可选的 setter 来间接获取和设置其他属性:
swift
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
// 计算属性
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0))
let initialCenter = square.center // (5.0, 5.0)
square.center = Point(x: 15.0, y: 15.0)
print("square.origin is now at (\(square.origin.x), \(square.origin.y))") // (10.0, 10.0)
3. 属性观察器
监视属性值的变化,在属性值发生改变时触发:
swift
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 200 // About to set totalSteps to 200; Added 200 steps
stepCounter.totalSteps = 360 // About to set totalSteps to 360; Added 160 steps
九、方法
方法是与特定类型关联的函数。
1. 实例方法
属于特定类实例、结构体实例或枚举实例的方法:
swift
class Counter {
var count = 0
// 实例方法
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
counter.increment()
print(counter.count) // 1
counter.increment(by: 5)
print(counter.count) // 6
counter.reset()
print(counter.count) // 0
2. 类型方法
属于类型本身的方法,使用 static
关键字(结构体和枚举)或 class
关键字(类)定义:
swift
class Math {
class func abs(_ x: Int) -> Int {
return x < 0 ? -x : x
}
}
print(Math.abs(-5)) // 5
struct Point {
var x: Int, y: Int
static func distance(from a: Point, to b: Point) -> Int {
let dx = a.x - b.x
let dy = a.y - b.y
return Int(sqrt(Double(dx*dx + dy*dy)))
}
}
let p1 = Point(x: 0, y: 0)
let p2 = Point(x: 3, y: 4)
print(Point.distance(from: p1, to: p2)) // 5
十、继承
继承允许一个类(子类)继承另一个类(父类)的特性,使用 :
表示继承关系。
swift
// 父类
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
// 空实现
}
}
// 子类
class Bicycle: Vehicle {
var hasBasket = false
}
let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
print("Bicycle: \(bicycle.description)") // Bicycle: traveling at 15.0 miles per hour
// 重写方法和属性
class Train: Vehicle {
override func makeNoise() {
print("Choo Choo")
}
}
let train = Train()
train.makeNoise() // Choo Choo
class Car: Vehicle {
var gear = 1
override var description: String {
return super.description + " in gear \(gear)"
}
}
let car = Car()
car.currentSpeed = 25.0
car.gear = 3
print("Car: \(car.description)") // Car: traveling at 25.0 miles per hour in gear 3
总结
Swift 是一门简洁、安全且功能强大的现代编程语言,其基础语法包括:
- 变量和常量(
let
/var
)及类型系统 - 可选类型(处理
nil
值) - 控制流语句(
if
/switch
/for
/while
) - 集合类型(数组、字典、集合)
- 函数和闭包(支持函数式编程)
- 结构体和类(面向对象编程基础)
- 属性和方法(数据和行为封装)
- 继承(代码复用机制)
Swift 的语法设计注重可读性和安全性,同时提供了灵活的抽象机制,使开发者能够编写出清晰、高效且易于维护的代码。对于 iOS/macOS 开发而言,掌握 Swift 基础语法是构建各类应用的前提。