飞速入门 Swift 语言

在编程的世界中,每一种新语言的学习之旅都以一个简单的问候开始,通常就是“Hello, world!”。Swift 语言也不例外。只需一行代码:

print("Hello, world!")

这行代码不仅是 Swift 语言的入门,更是它强大简洁语法的缩影。在 Swift 中,无需导入额外库即可实现文本输出,程序的入口点直接由全局作用域的代码决定,这意味着你不再需要像 C 语言那样写一个 main()​函数。此外,Swift 还省略了每条语句后的分号,使得代码更加清晰易读。

🔍 基础概念:常量与变量

在 Swift 中,使用 let​定义常量,用 var​定义变量。常量的值在编译时不必知道,但必须赋值一次。这样的设计使得常量可以用来命名一个只需确定一次的值,而在多个地方使用。

var myVariable = 42
myVariable = 50
let myConstant = 42

值得注意的是,常量或变量的类型必须与赋值的值一致。Swift 的编译器能根据初始值推断变量类型。例如,上述代码中,myVariable​被推断为整型。如果初始值无法提供足够的信息,或没有初始值,则需要显式指定类型。

let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70

🧪 实验:创建常量

试着创建一个明确类型为 Float​且值为 4 的常量。

Swift 中,值不会被隐式转换为另一种类型。如果需要转换,则必须显式创建目标类型的实例。例如:

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

如果你尝试移除最后一行中的转换,Swift 会报错。

🍏 字符串插值

在字符串中插入值更简单的方法是使用 \(value)​,例如:

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

如果需要多行字符串,可以使用三重引号("""​),Swift 会自动移除开头和结尾相同缩进的空格。

let quotation = """
    Even though there's whitespace to the left,
    the actual lines aren't indented.
        Except for this line.
"""

📦 数组与字典

Swift 中的数组和字典使用方括号([]​)创建,并通过索引或键来访问元素。创建空数组或字典时,可以直接使用 []​或 [:]​。

var fruits = ["strawberries", "limes", "tangerines"]
fruits[1] = "grapes"

var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

数组会随着元素的增加而自动增长。

fruits.append("blueberries")
print(fruits)
// Prints "["strawberries", "grapes", "tangerines", "blueberries"]"

🔄 控制流

Swift 使用 if​和 switch​来进行条件判断,使用 for-in​、while​和 repeat-while​来进行循环。条件或循环变量的括号是可选的,但代码块的花括号是必须的。

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
print(teamScore)
// Prints "11"

if​语句中,条件必须是布尔表达式,这意味着像 if score { ... }​这样的代码是错误的。

🎉 使用条件选择

你可以在赋值或返回语句中使用 if​或 switch​来选择值。例如:

let scoreDecoration = if teamScore > 10 {
    "🎉"
} else {
    ""
}
print("Score:", teamScore, scoreDecoration)
// Prints "Score: 11 🎉"

🛠️ 函数与闭包

使用 func​声明函数,并通过参数列表调用函数。返回类型用 ->​分隔。

func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")

🧩 使用元组返回多个值

你可以使用元组创建复合值。例如,返回多个值:

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0

    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
  
    return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)  // Prints "120"

🏗️ 对象与类

使用 class​创建类,类中的属性声明与常量或变量声明相同。方法和函数的声明也是如此。

class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

创建类的实例,只需在类名后加括号。

var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()

🏆 继承与重写

子类在类名后加上超类名,用冒号分隔。重写的方法用 override​标记。

class Square: NamedShape {
    var sideLength: Double

    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 4
    }

    func area() -> Double {
        return sideLength * sideLength
    }

    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."
    }
}

🎨 枚举和结构体

使用 enum​创建枚举,枚举可以有与之相关联的方法。

enum Rank: Int {
    case ace = 1
    case two, three, four, five, six, seven, eight, nine, ten
    case jack, queen, king

    func simpleDescription() -> String {
        switch self {
        case .ace:
            return "ace"
        case .jack:
            return "jack"
        case .queen:
            return "queen"
        case .king:
            return "king"
        default:
            return String(self.rawValue)
        }
    }
}

📝 结构体的定义

使用 struct​创建结构体,结构体拥有与类相似的行为。

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}

⚛️ 并发编程

使用 async​标记异步函数,调用异步函数时需在前面加上 await​。

func fetchUserID(from server: String) async -> Int {
    if server == "primary" {
        return 97
    }
    return 501
}

🧩 使用任务组

使用 Task​从同步代码调用异步函数,而不等待它们返回。

Task {
    await connectUser(to: "primary")
}

📜 协议与扩展

使用 protocol​声明协议。类、枚举和结构体都可以采用协议。

protocol ExampleProtocol {
    var simpleDescription: String { get }
    mutating func adjust()
}

🔧 使用扩展增加功能

通过 extension​为现有类型添加功能,例如新方法和计算属性。

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}

💥 错误处理

使用 enum​表示错误类型,使用 throw​抛出错误,使用 do-catch​处理错误。

enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire
}

🔑 泛型

通过在尖括号中写名称来创建泛型函数或类型。

func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
    var result: [Item] = []
    for _ in 0..<numberOfTimes {
        result.append(item)
    }
    return result
}

结语

Swift 语言如同一把锋利的工具,让开发者能以优雅的方式解决复杂问题。在这一场编程的旅程中,Swift 以其简洁、高效和安全的特性,成为了现代开发者的得力助手。

参考文献

  1. Apple. Swift Programming Language. https://swift.org/documentation/
  2. Apple. The Swift Language Guide. https://docs.swift.org/swift-book/
  3. Hacking with Swift. Swift Programming Language. https://www.hackingwithswift.com/
  4. Ray Wenderlich. Swift Tutorial for Beginners. https://www.raywenderlich.com/
  5. Paul Hudson. 100 Days of Swift. https://www.hackingwithswift.com/100/swiftui
  • Swift

    Swift 是苹果于 2014 年 WWDC(苹果开发者大会)发布的开发语言,可与 Objective-C 共同运行于 Mac OS 和 iOS 平台,用于搭建基于苹果平台的应用程序。

    36 引用 • 37 回帖 • 520 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...