Swift基础(二)
温馨提示:
本文最后更新于 2026年01月16日,已超过 16 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
10 集合set
Set 用于存储 无序、不重复 的同类型元素。
10.1 Set 的声明
10.1.1 使用字面量声明
var fruits: Set<String> = ["Apple", "Banana", "Orange"]
⚠️ 注意:
- 必须显式声明为
Set,否则会被推断为Array
10.2 插入和删除元素
10.2.1 插入元素
fruits.insert("Pear")
10.2.2 删除元素
fruits.remove("Apple")
10.3 判断和查找
10.3.1 是否包含元素
fruits.contains("Banana")
10.4 Set 运算
10.4.1 交集 / 并集 / 差集
let a: Set = [1, 2, 3]
let b: Set = [3, 4, 5]
a.intersection(b) // 交集
a.union(b) // 并集
a.subtracting(b) // 差集
a.symmetricDifference(b)// 对称差集
11 字典
字典用于存储 键值对(Key-Value),Key 唯一。
11.1 字典声明
11.1.1 字面量方式
var scores = ["Tom": 90, "Jack": 80]
11.1.2 显式类型声明
var ages: [String: Int] = [:]
11.2 访问和修改
11.2.1 通过 Key 访问
scores["Tom"] // 返回 Optional<Int>
11.2.2 修改或添加键值
scores["Lucy"] = 95
scores["Tom"] = 100
11.3 删除元素
11.3.1 删除指定 Key
scores.removeValue(forKey: "Jack")
11.4 字典遍历
11.4.1 遍历键值对
for (name, score) in scores {
print(name, score)
}
11.5 常用属性
11.5.1 keys / values
scores.keys
scores.values
scores.count
12 区间
12.1 区间类型
12.1.1 闭区间
1...5 // 包含 1 和 5
12.1.2 半开区间
1..<5 // 包含 1,不包含 5
12.2 区间的使用场景
12.2.1 用于循环
for i in 1...3 {
print(i)
}
12.2.2 数组切片
let arr = [10, 20, 30, 40]
let sub = arr[1...2]
13 元组
元组用于将 多个不同类型的值 组合成一个整体。
13.1 元组的定义
13.1.1 基本元组
let person = ("Tom", 18)
13.2 访问元组元素
13.2.1 使用索引访问
person.0
person.1
13.2.2 命名元素
let user = (name: "Lucy", age: 20)
user.name
user.age
13.3 元组解包
13.3.1 解构赋值
let (name, age) = person
14 可选类型
Optional 是 Swift 最核心、最重要的特性之一。
14.1 什么是 Optional
14.1.1 nil 的安全处理
var value: Int? = nil
表示:
- 有值(Int)
- 或没有值(nil)
14.2 Optional 绑定
14.2.1 if let
if let v = value {
print(v)
}
14.3 强制解包
14.3.1 使用 !
let v = value!
⚠️ 不安全,可能导致崩溃
14.4 可选链
14.4.1 使用 ?
person?.name
14.5 nil 合并运算符
14.5.1 ??
let result = value ?? 0
15 循环语句
15.1 for-in 循环
15.1.1 遍历区间
for i in 1...3 {
print(i)
}
15.2 while 循环
15.2.1 条件循环
var i = 0
while i < 3 {
print(i)
i += 1
}
15.3 repeat-while
15.3.1 至少执行一次
repeat {
print("run")
} while false
16 条件语句 if
16.1 if 基本用法
16.1.1 单条件
if age >= 18 {
print("成年人")
}
16.2 if-else
16.2.1 双分支
if score >= 60 {
print("及格")
} else {
print("不及格")
}
16.3 多条件判断
16.3.1 else if
if score >= 90 {
print("优秀")
} else if score >= 60 {
print("及格")
} else {
print("不及格")
}
17 swicth 语句
17.1 switch 基本结构
17.1.1 基本示例
let level = "A"
switch level {
case "A":
print("优秀")
case "B":
print("良好")
default:
print("其他")
}
17.2 switch 的强大特性
17.2.1 不需要 break
// Swift 自动终止,不会贯穿
17.2.2 支持区间匹配
switch score {
case 90...100:
print("优秀")
case 60..<90:
print("及格")
default:
print("不及格")
}
17.2.3 元组匹配
let point = (1, 0)
switch point {
case (0, 0):
print("原点")
case (_, 0):
print("X轴")
case (0, _):
print("Y轴")
default:
print("其他")
}
18 函数
函数是 Swift 中组织代码、复用逻辑的核心单位。
18.1 函数的基本定义
18.1.1 无参数、无返回值
func sayHello() {
print("Hello Swift")
}
调用:
sayHello()
18.2 带参数的函数
18.2.1 单参数函数
func greet(name: String) {
print("Hello \(name)")
}
18.2.2 多参数函数
func add(a: Int, b: Int) {
print(a + b)
}
18.3 带返回值的函数
18.3.1 返回 Int
func sum(a: Int, b: Int) -> Int {
return a + b
}
18.3.2 返回 Bool
func isAdult(age: Int) -> Bool {
return age >= 18
}
18.4 参数标签(Swift 特有)
18.4.1 外部参数名
func greet(to name: String) {
print("Hello \(name)")
}
greet(to: "Tom")
18.4.2 省略外部参数名
func multiply(_ a: Int, _ b: Int) -> Int {
a * b
}
18.5 默认参数值
18.5.1 默认参数
func connect(host: String = "localhost", port: Int = 8080) {
print(host, port)
}
18.6 可变参数
18.6.1 使用 ...
func average(_ numbers: Int...) -> Double {
let total = numbers.reduce(0, +)
return Double(total) / Double(numbers.count)
}
18.7 函数示例(综合)
18.7.1 登录校验
func login(user: String, password: String) -> Bool {
return user == "admin" && password == "123456"
}
18.7.2 计算折扣价格
func finalPrice(price: Double, discount: Double = 0.9) -> Double {
price * discount
}
19 枚举类型
枚举用于定义 一组有限、明确的取值,在 Swift 中非常强大。
19.1 基本枚举
19.1.1 简单枚举
enum Direction {
case north
case south
case east
case west
}
19.2 使用枚举
19.2.1 switch 匹配
let dir = Direction.north
switch dir {
case .north:
print("向北")
case .south:
print("向南")
default:
print("其他方向")
}
19.3 原始值枚举
19.3.1 Int 原始值
enum Weekday: Int {
case monday = 1
case tuesday
case wednesday
}
19.3.2 String 原始值
enum APIStatus: String {
case success = "200"
case notFound = "404"
}
19.4 关联值枚举(重点)
19.4.1 定义关联值
enum Result {
case success(data: String)
case failure(error: String)
}
19.4.2 使用关联值
let res = Result.success(data: "OK")
switch res {
case .success(let data):
print(data)
case .failure(let error):
print(error)
}
19.5 枚举方法
19.5.1 枚举中定义函数
enum Level {
case low, medium, high
func description() -> String {
switch self {
case .low: return "低"
case .medium: return "中"
case .high: return "高"
}
}
}
20 闭包
闭包是 可被传递、存储的代码块,是 SwiftUI 的核心。
20.1 闭包基本形式
20.1.1 完整写法
let add = { (a: Int, b: Int) -> Int in
return a + b
}
20.2 闭包简写规则
20.2.1 参数省略
let add: (Int, Int) -> Int = {
$0 + $1
}
20.3 闭包作为参数
20.3.1 函数接收闭包
func calculate(a: Int, b: Int, operation: (Int, Int) -> Int) -> Int {
operation(a, b)
}
调用:
calculate(a: 3, b: 5) { $0 + $1 }
20.4 常见使用场景
20.4.1 数组排序
let nums = [3, 1, 2]
let sorted = nums.sorted { $0 > $1 }
21 结构体(struct)
结构体是 值类型,Swift 中使用频率极高。
21.1 定义结构体
21.1.1 基本结构体
struct User {
var name: String
var age: Int
}
21.2 使用结构体
21.2.1 创建实例
var user = User(name: "Tom", age: 18)
user.age = 20
21.3 方法和属性
21.3.1 定义方法
struct Rectangle {
var width: Double
var height: Double
func area() -> Double {
width * height
}
}
21.4 mutating 方法
21.4.1 修改自身
struct Counter {
var value = 0
mutating func increment() {
value += 1
}
}
22 类
22.1 定义类
22.1.1 基本类
class Animal {
var name: String
init(name: String) {
self.name = name
}
func speak() {
print("Animal sound")
}
}
22.2 继承
22.2.1 子类
class Dog: Animal {
override func speak() {
print("Woof")
}
}
22.3 引用特性
22.3.1 引用语义示例
let dog1 = Dog(name: "Lucky")
let dog2 = dog1
dog2.name = "Tom"
print(dog1.name) // Tom
23 SwiftUI 语言衔接
23.1 View 基本结构
23.1.1 最简单的 SwiftUI View
struct ContentView: View {
var body: some View {
Text("Hello SwiftUI")
}
}
23.2 Swift 基础在 SwiftUI 中的体现
23.2.1 使用变量和条件
struct ContentView: View {
let isLogin = true
var body: some View {
if isLogin {
Text("欢迎")
} else {
Text("请登录")
}
}
}
23.3 枚举 + switch 驱动 UI
23.3.1 状态枚举
enum PageState {
case loading
case success
case error
}
switch state {
case .loading:
ProgressView()
case .success:
Text("成功")
case .error:
Text("失败")
}
23.4 闭包在 SwiftUI 中的核心作用
23.4.1 Button 闭包
Button("点击") {
print("按钮点击")
}
23.5 struct + 状态驱动 UI
23.5.1 @State 示例
struct CounterView: View {
@State private var count = 0
var body: some View {
Button("点击 \(count)") {
count += 1
}
}
}
正文到此结束
- 本文标签: swift
- 本文链接: https://www.tianyajuanke.top/article/98
- 版权声明: 本文由吴沛芙原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权