Swift 基本语法

Swift 基本语法全解析(2025 版)

掌握这 15 个核心语法点,30 分钟让你写出地道 Swift 代码!


一、变量与常量

var name = "小明"        // 可变变量
let age = 18            // 不可变常量(优先使用 let)

name = "小红"           // OK
// age = 20             // 错误!常量不可变

类型推断:Swift 自动识别类型
显式声明var score: Int = 95


二、基本数据类型

类型示例说明
Intlet count = 10整数(64 位)
Doublelet pi = 3.14双精度浮点
Floatlet f: Float = 3.14单精度
Boollet isActive = true布尔值
Stringlet greeting = "Hello"字符串
Characterlet c: Character = "A"单个字符
let height = 1.78          // Double
let weight = 65            // Int
let name = "张三"           // String

三、字符串操作(超强大)

let str = "Swift 真香!"

// 拼接
let full = str + " 🚀"

// 插值
let score = 95
print("得分:\(score) 分")  // 得分:95 分

// 多行字符串
let poem = """
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
"""

// 常用方法
str.count
str.hasPrefix("Sw")
str.uppercased()
str.contains("香")

四、数组(Array)

var fruits = ["苹果", "香蕉", "橙子"]

// 添加
fruits.append("葡萄")
fruits += ["西瓜"]

// 修改
fruits[1] = "火龙果"

// 删除
fruits.remove(at: 0)
fruits.removeLast()

// 遍历
for fruit in fruits {
    print(fruit)
}

// 带索引
for (index, fruit) in fruits.enumerated() {
    print("\(index): \(fruit)")
}

常用属性:.count, .isEmpty, .first, .last


五、字典(Dictionary)

var scores = [
    "张三": 95,
    "李四": 88,
    "王五": 70
]

// 添加/修改
scores["赵六"] = 82

// 读取(安全)
if let s = scores["李四"] {
    print("李四得分:\(s)")
}

// 默认值
let zhao = scores["赵六"] ?? 0

// 删除
scores["王五"] = nil

// 遍历
for (name, score) in scores {
    print("\(name): \(score)分")
}

六、集合(Set)

var colors: Set = ["红", "绿", "蓝"]
colors.insert("黄")
colors.remove("绿")

let hasBlue = colors.contains("蓝")  // true

// 集合运算
let setA: Set = [1, 2, 3, 4]
let setB: Set = [3, 4, 5, 6]

let union = setA.union(setB)           // 并集
let intersection = setA.intersection(setB) // 交集
let difference = setA.subtracting(setB)    // 差集

七、控制流

1. if 语句

let temp = 25

if temp < 0 {
    print("冰冻")
} else if temp < 10 {
    print("寒冷")
} else if temp < 25 {
    print("舒适")
} else {
    print("炎热")
}

2. switch 语句(超级强大!)

let grade = "A"

switch grade {
case "A":
    print("优秀")
case "B", "C":          // 多匹配
    print("良好")
case let x where x >= "D":
    print("及格")
default:
    print("未知")
}

区间匹配

let score = 88

switch score {
case 90...100:
    print("A")
case 80..<90:
    print("B")
case 70..<80:
    print("C")
default:
    print("D")
}

元组匹配

let point = (3, 0)

switch point {
case (0, 0):
    print("原点")
case (_, 0):
    print("x轴")
case (0, _):
    print("y轴")
case let (x, y) where x == y:
    print("对角线")
default:
    print("其他")
}

八、循环

1. for-in

// 数字区间
for i in 1...5 {
    print(i)
}

// 数组
for fruit in fruits {
    print(fruit)
}

// 跳步
for i in stride(from: 0, to: 10, by: 2) {
    print(i)  // 0,2,4,6,8
}

2. while

var n = 5
while n > 0 {
    print(n)
    n -= 1
}

// repeat-while(至少执行一次)
repeat {
    print("执行")
} while false

九、可选类型(Optional)—— Swift 核心!

var optionalName: String? = "张三"
optionalName = nil

// 1. 强制解包(危险!)
print(optionalName!)  // 运行时崩溃如果为 nil

// 2. 可选绑定(推荐!)
if let name = optionalName {
    print("名字:\(name)")
} else {
    print("无名字")
}

// 3. 空合运算符
let display = optionalName ?? "匿名"

// 4. 可选链
struct Person {
    var dog: Dog?
}
struct Dog {
    var name = "旺财"
}

let person: Person? = Person()
let dogName = person?.dog?.name  // 可选链

十、函数

// 基本函数
func greet(name: String) -> String {
    return "你好,\(name)!"
}

// 多参数 + 默认值
func power(base: Int, exponent: Int = 2) -> Int {
    return Int(pow(Double(base), Double(exponent)))
}

print(power(base: 3))     // 9
print(power(base: 3, exponent: 3)) // 27

// 参数标签
func sayHello(to name: String) {
    print("Hello, \(name)!")
}
sayHello(to: "Tom")  // 必须写 to

// 返回多个值(元组)
func minMax(_ numbers: [Int]) -> (min: Int, max: Int)? {
    guard !numbers.isEmpty else { return nil }
    return (numbers.min()!, numbers.max()!)
}

十一、闭包(Closure)

// 完整写法
let add = { (a: Int, b: Int) -> Int in
    return a + b
}

// 简写
let multiply = { $0 * $1 }

// 实际使用:数组排序
let names = ["张三", "李四", "王五"]
let sorted = names.sorted { $0.count < $1.count }

// map/filter/reduce
let nums = [1, 2, 3, 4]
let doubled = nums.map { $0 * 2 }           // [2,4,6,8]
let evens = nums.filter { $0 % 2 == 0 }    // [2,4]
let sum = nums.reduce(0) { $0 + $1 }       // 10

十二、guard 语句(提前退出)

func checkAge(_ age: Int?) {
    guard let age = age, age >= 18 else {
        print("未成年")
        return
    }
    print("已成年,年龄:\(age)")
}

十三、枚举(Enum)

enum Direction {
    case up, down, left, right
}

let move = Direction.up

switch move {
case .up: print("向上")
default: print("其他")
}

// 带关联值
enum Result {
    case success(String)
    case failure(Error)
}

let result = Result.success("登录成功")

// 带原始值
enum Grade: String {
    case excellent = "A"
    case good = "B"
}

十四、结构体 vs 类

特性StructClass
类型值类型引用类型
复制复制引用
继承不支持支持
struct Point {
    var x, y: Int
}

class Car {
    var speed = 0
    func go() { speed += 10 }
}

十五、错误处理

enum LoginError: Error {
    case wrongPassword
    case userNotFound
}

func login(username: String, password: String) throws {
    if username.isEmpty { throw LoginError.userNotFound }
    if password != "123" { throw LoginError.wrongPassword }
}

// 使用
do {
    try login(username: "", password: "123")
} catch LoginError.userNotFound {
    print("用户不存在")
} catch {
    print("其他错误:\(,error)")
}

语法速查表

语法示例
注释// 单行
/* 多行 */
类型转换String(123)
Int("123")
断言assert(age > 0, "年龄错误")
打印print(items:separatedBy:)
三元运算age > 18 ? "成人" : "未成年"

小练习(当场写!)

// 1. 打印 1 到 100 的奇数
for i in 1...100 where i % 2 == 1 {
    print(i)
}

// 2. 统计字符串中每个字符出现次数
let str = "hello"
var count: [Character: Int] = [:]
for c in str {
    count[c, default: 0] += 1
}
print(count)

下一步?

你已掌握 Swift 核心语法
接下来建议:

  1. SwiftUI 界面开发 → 做个计算器
  2. Swift Package 命令行工具 → 写个 Todo CLI
  3. iOS App 实战 → 天气/记事本

回复关键词继续学习

  • SwiftUI 入门
  • iOS 项目实战
  • Swift 算法练习

现在就打开 Playground,敲 10 行代码试试!

文章已创建 2481

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部