TOC

Swift 语言

Swift 是基于 Apache 2.0 协议开源。
Swift 可以在 Linux 上运行,并且使用 Clang/LLVM 编译器。

  • 强类型、静态类型、编译型、类型安全
  • 使用自动引用计数 (ARC) 来管理内存
  • 面向对象编程
    • 面向协议编程,其实就是面向对象中的接口
  • 函数式编程
protocol Vehicle {
    func drive()
}

protocol Electric: Vehicle {
    func charge()
}

struct ElectricCar: Electric {
    func drive() {
        print("Electric car is driving")
    }

    func charge() {
        print("Charging electric car")
    }
}

关键字

以下是一个表格,列出了 Swift 中的所有关键字,并将它们按类别分类:

类别 关键字 描述
基本类型 Bool 布尔类型
Int 整数类型
Double 双精度浮点类型
Float 单精度浮点类型
String 字符串类型
控制流 if 条件判断语句
else if 配合使用的条件判断语句
switch 用于多条件分支的控制流
case switch 语句中的分支条件
default switch 语句中的默认分支
while while 循环
for 用于循环的控制流
continue 跳过本轮循环,继续执行下一次循环
break 终止当前的循环或 switch 语句
存储类型 let 声明常量
var 声明变量
函数/方法 func 函数声明
return 从函数返回
inout 用于函数参数,表示参数是传递引用
defer 在作用域结束时执行的语句块
类型 class 定义类
struct 定义结构体
enum 定义枚举
protocol 定义协议
extension 扩展现有类型
对象/类 self 引用当前实例
super 引用父类实例
init 初始化方法
deinit 析构方法
控制 guard 条件判断语句,通常用于提前退出函数或方法
访问控制 public 公开访问权限
internal 默认的访问权限
private 私有访问权限
fileprivate 文件私有访问权限
错误处理 try 用于调用抛出错误的函数
catch 捕获错误的语句
throw 抛出错误
throws 声明函数可能抛出错误
可选类型 Optional 表示值可能为 nil
nil 表示可选类型的空值
其他 typealias 定义类型别名
associatedtype 协议中定义的关联类型
where 用于指定条件,通常与 forswitch 配合使用
is 类型检查运算符
as 类型转换运算符
any 表示可以是任何类型
some 用于定义某个类型的泛型约束
indirect 用于枚举声明,表示枚举值是通过递归引用的

数据类型

// 整数类型
var age: Int = 20

// 浮点数类型
var weight: Double = 65.5

// 字符串类型
var name: String = "Alice"

// 布尔类型
var isPassed: Bool = true

// 数组类型
var scores: [Int] = [85, 90, 78, 92]

// 字典类型
var studentInfo: [String: Any] = [
    "name": "Alice",
    "age": 20,
    "scores": [85, 90, 78, 92]
]

// 元组类型
var student: (name: String, age: Int, scores: [Int]) = ("Alice", 20, [85, 90, 78, 92])

// 可选类型
var grade: String? = "A"
var address: String? = nil // 没有地址

逻辑控制

// if 语句
if age >= 18 {
    print("\(name) is an adult.")
} else {
    print("\(name) is a minor.")
}

// switch 语句
switch grade {
case "A":
    print("\(name) has excellent grades!")
case "B":
    print("\(name) has good grades.")
default:
    print("\(name) needs improvement.")
}

// for-in 循环
for score in scores {
    print("Score: \(score)")
}

// while 循环
var index = 0
while index < scores.count {
    print("Score at index \(index): \(scores[index])")
    index += 1
}

运算符

// 算术运算符
let sum = 5 + 3       // 加法
let difference = 5 - 3 // 减法
let product = 5 * 3    // 乘法
let quotient = 5 / 3   // 除法
let remainder = 5 % 3  // 取余

// 比较运算符
let isEqual = (5 == 3) // 等于
let isGreater = (5 > 3) // 大于
let isLess = (5 < 3)    // 小于

// 逻辑运算符
let isTrue = true
let isFalse = false
let andResult = isTrue && isFalse // 与运算
let orResult = isTrue || isFalse  // 或运算
let notResult = !isTrue           // 非运算

函数

// 计算平均分
func calculateAverage(scores: [Int]) -> Double {
    let total = scores.reduce(0, +)
    return Double(total) / Double(scores.count)
}

// 判断是否及格
func isPassing(average: Double) -> Bool {
    return average >= 60
}

// 使用函数
let averageScore = calculateAverage(scores: scores)
print("Average score: \(averageScore)")

if isPassing(average: averageScore) {
    print("\(name) passed the exam.")
} else {
    print("\(name) failed the exam.")
}

面向对象编程

// 定义一个类
class Student {
    var name: String
    var age: Int
    var scores: [Int]

    // 初始化方法
    init(name: String, age: Int, scores: [Int]) {
        self.name = name
        self.age = age
        self.scores = scores
    }

    // 方法:计算平均分
    func calculateAverage() -> Double {
        let total = scores.reduce(0, +)
        return Double(total) / Double(scores.count)
    }

    // 方法:判断是否及格
    func isPassing() -> Bool {
        return calculateAverage() >= 60
    }
}

// 创建对象
let student1 = Student(name: "Alice", age: 20, scores: [85, 90, 78, 92])

// 使用类的方法
let average = student1.calculateAverage()
print("Average score of \(student1.name): \(average)")

if student1.isPassing() {
    print("\(student1.name) passed the exam.")
} else {
    print("\(student1.name) failed the exam.")
}
如果你有魔法,你可以看到一个评论框~