您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

Swift 語言全解析:從 Hello World 到泛型的核心語法入門

編輯:iOS 相關教學

2014 年的 WWDC 上,蘋果端出了一份意料之外的驚喜——一門名為 Swift 的全新編程語言。它肩負的使命很明確:成為 iOS 與 OS X 應用開發的主力工具,同時把 Objective-C 時代積累的繁瑣與笨重一併丟掉。

一、Swift 究竟是什麼?

官方手冊《The Swift Programming Language》的開篇是這樣定義的:

Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility.
Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible and more fun.
Swift's clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to imagine how software development works.
Swift is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.

翻成白話,可以拆成四個要點來理解:

  • Swift 面向 iOS 與 OS X 平台的應用開發,一開始並沒有打算成為跨平台通用語言。
  • 它吸收了 C 與 Objective-C 的精華,卻擺脫了 C 兼容性帶來的歷史包袱。
  • 它可以直接調用既有的 Cocoa 與 Cocoa Touch 框架,不必推倒重來。
  • 它同時具備編譯型語言的執行效能與腳本語言的即時反饋特性。

二、Swift 語言概覽

以下範例整理自官方手冊中的「A Swift Tour」,是最直觀的語法速覽。

1. 基本概念

1.1 Hello, world

和腳本語言一樣輕快,一行就是一個完整可執行的程序:

println("Hello, world")

1.2 變數與常量

var 宣告變數,let 宣告常量:

var myVariable = 42
myVariable = 50
let myConstant = 42

1.3 型別推導

Swift 具備型別推導(Type Inference)能力,因此上面的宣告都不必標註型別。若你希望明確指定:

let explicitDouble: Double = 70

值得注意的是,Swift 不允許隱式型別轉換(implicit casting),所有轉換都得寫清楚:

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

1.4 字串插值

把值嵌進字串,寫法是用反斜線加括號 \(item):

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

1.5 陣列與字典

兩者都靠 [] 語法表達:

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"

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

建立空集合時,通常透過初始化器語法:

let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()

若型別資訊已在別處確定,也可以簡寫成 [] 與 [:]。

2. 控制流

2.1 基本結構

條件判斷有 if 與 switch,迴圈則有 for-in、for、while 與 do-while。一個容易上手也容易忘的規則:條件運算式不寫括號,但迴圈或判斷的主體必須用大括號包住。

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}

2.2 可空型別

搭配 if 與 let,處理可能為空的變數變得相當乾淨。宣告時在型別後加上 ?,即表示這個值允許為 nil:

var optionalString: String? = "Hello"
optionalString == nil

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}

2.3 靈活的 switch

Swift 的 switch 支援的比較方式遠比 C 豐富,還能帶條件綁定:

let vegetable = "red pepper"
switch vegetable {
case "celery":
    let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
    let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
    let vegetableComment = "Is it a spicy \(x)?"
default:
    let vegetableComment = "Everything tastes good in soup."
}

2.4 其他迴圈形式

for-in 不只遍歷陣列,也能直接拆解字典的鍵值:

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest

while 與 do-while 的行為與多數語言一致:

var n = 2
while n < 100 {
    n = n * 2
}

var m = 2
do {
    m = m * 2
} while m < 100
m

傳統三段式 for 仍然保留,同時也可以用範圍運算子搭配 for-in 達到相同效果:

var firstForLoop = 0
for i in 0..3 {
    firstForLoop += i
}

var secondForLoop = 0
for var i = 0; i < 3; ++i {
    secondForLoop += 1
}

別把兩個範圍運算子搞混:.. 是前閉後開區間,... 是前閉後閉區間。

3. 函數與閉包

3.1 函數

用 func 宣告函數:

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

需要一次回傳多個值時,用元組(tuple)即可:

func getGasPrices() -> (Double, Double, Double) {
    return (3.59, 3.69, 3.79)
}
getGasPrices()

參數數量不固定時,用變長參數:

func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf()
sumOf(42, 597, 12)

函數也能嵌套定義:

func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()

函數在 Swift 裡是一等公民,既能當回傳值,也能當參數傳遞:

func makeIncrementer() -> (Int -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()
increment(7)

func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}

func lessThanTen(number: Int) -> Bool {
    return number < 10
}

var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)

3.2 閉包

本質上,函數就是一種特殊的閉包。用 {} 可以寫出匿名閉包:

numbers.map({
    (number: Int) -> Int in
    let result = 3 * number
    return result
})

當型別已被推導出來時,可以大幅精簡:

numbers.map({ number in 3 * number })

甚至可以省略參數名,改用位置參數 $0、$1。若函數的最後一個參數是閉包,還能把它移到括號外:

sort([1, 5, 3, 12, 2]) { $0 > $1 }

4. 類與物件

4.1 定義與使用類

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()

透過 init 完成物件初始化。這裡同時示範了兩種引用方式:用 self 顯式指向成員,或如 numberOfSides 般隱式引用:

class NamedShape {
    var numberOfSides: Int = 0
    var name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

若要進行資源清理,則定義 deinit。

4.2 繼承與多型

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)."
    }
}

let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()

覆寫父類方法時,override 標記不是可選項——漏寫就是編譯錯誤。這個設計能有效避免無意間意外覆蓋。

4.3 屬性

屬性(property)讓計算結果可以像普通欄位一樣被讀寫:

class EquilateralTriangle: NamedShape {
    var sideLength: Double = 0.0

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

    var perimeter: Double {
        get {
            return 3.0 * sideLength
        }
        set {
            sideLength = newValue / 3.0
        }
    }

    override func simpleDescription() -> String {
        return "An equilateral triangle with sides of length \(sideLength)."
    }
}

var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
triangle.perimeter
triangle.perimeter = 9.9
triangle.sideLength

setter 裡傳入的值會被自動命名為 newValue。

4.4 willSet 與 didSet

子類的初始化通常依序做三件事:設定自己的屬性、呼叫父類初始化器、修改父類屬性。若你不需要計算屬性的值,只想在賦值前後插入一些行為,willSet 與 didSet 就是答案:

class TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}

var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square.sideLength
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
triangleAndSquare.triangle.sideLength

如此一來,三角形與正方形的邊長永遠同步。

4.5 方法呼叫與參數別名

函數的參數名稱僅在函數內部有效;而方法的參數名稱除了內部可用,外部呼叫時也能使用(第一個參數除外):

class Counter {
    var count: Int = 0
    func incrementBy(amount: Int, numberOfTimes times: Int) {
        count += amount * times
    }
}
var counter = Counter()
counter.incrementBy(2, numberOfTimes: 7)

上面這段程式碼裡,numberOfTimes 面向外部呼叫者,times 則是函式內部使用的名稱。

4.6 可空值的另一種用法

? 也可以放在方法、屬性或下標之前。若前面的值為 nil,後面的整串運算式會被跳過,結果直接是 nil:

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optionalSquare")
let sideLength = optionalSquare?.sideLength

5. 列舉與結構

5.1 列舉

用 enum 建立列舉,而 Swift 的列舉可以關聯方法——這點比多數語言走得更遠:

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"
        }
    }
}
let ace = Rank.Ace
let aceRawValue = ace.toRaw()

原始值(raw value)與列舉值之間可以透過 toRaw 與 fromRaw 互相轉換:

if let convertedRank = Rank.fromRaw(3) {
    let threeDescription = convertedRank.simpleDescription()
}

要牢記的是:成員值(member value)才是真正被使用的值,它和原始值之間並無必然關聯。有些列舉甚至沒有有意義的原始值,這時直接省略就好:

enum Suit {
    case Spades, Hearts, Diamonds, Clubs

    func simpleDescription() -> String {
        switch self {
        case .Spades:
            return "spades"
        case .Hearts:
            return "hearts"
        case .Diamonds:
            return "diamonds"
        case .Clubs:
            return "clubs"
        }
    }
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDescription()

更有趣的是,列舉成員還能各自關聯不同的值:

enum ServerResponse {
    case Result(String, String)
    case Error(String)
}

let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")

switch success {
case let .Result(sunrise, sunset):
    let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
    let serverResponse = "Failure... \(error)"
}

5.2 結構

用 struct 建立結構。結構同樣支援初始化器與方法,與類最大的差別在於傳遞方式:結構實例是值傳遞(passed by value),類實例則是參考傳遞(passed by reference)。

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()

5.3 協議與擴展

協議用 protocol 定義,類、列舉、結構都能實作它:

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

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple class."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += " Now 100% adjusted."
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription

struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

結構的 adjust() 需要標記 mutating,因為它會修改實例本身。

擴展(extension)則是用來替既有型別加上新功能:

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

5.4 泛型

泛型函數或泛型型別以 <> 宣告:

func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
    var result = ItemType[]()
    for i in 0..times {
        result += item
    }
    return result
}
repeat("knock", 4)

類、列舉與結構也都能使用泛型:

// Reimplement the Swift standard library's optional type
enum OptionalValue<T> {
    case None
    case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)

當泛型需要附加條件——例如要求實作某個協議、繼承某個特定型別,或要求兩個泛型參數的元素型別相同——就用 where 描述:

func anyCommonElements <T, U where T: Sequence,
U: Sequence, T.GeneratorType.Element: Equatable,
T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}
anyCommonElements([1, 2, 3], [3])

三、幾點個人觀察

以下純屬個人看法,僅供參考。

大雜燴,但是是精心挑過的那種

即使只花了不到兩小時接觸 Swift,也很容易看出它從其他語言身上取用了大量元素:

  • 屬性、可空型別語法與泛型語法,有濃厚的 C# 影子。
  • 程式碼風格接近 Go:沒有行尾分號,判斷條件不寫括號。
  • self 的用法、以及陣列與字典的宣告語法,帶著 Python 的味道。
  • 1..3、1...3 這類區間語法則是 Haskell 風格。
  • 協議與擴展沿用自家 Objective-C 的概念。
  • 列舉可以擁有成員與方法,很像 Java;class 與 struct 的分工也和 C# 極為相似。

這並不構成抄襲的指控——程式語言能玩的花樣本來就有限,何況 Swift 挑選的幾乎都是相當優秀的特性。而這種「大雜燴」反而帶來一個關鍵優勢:任何來自其他語言背景的開發者,都不會覺得 Swift 陌生。

拒絕隱式行為

Swift 果斷砍掉了隱式型別轉換與隱式方法重載這兩個長年埋坑的設計,值得喝采。

它可能的兩個主要方向

教育。現有程式語言最大的問題之一是互動性奇差,學習曲線因此陡峭得令人卻步。Swift 搭配高互動性的開發環境,有機會改變這個局面,讓更多人以青少年更容易接受的方式踏入程式設計。想了解互動式編程環境能帶來什麼,Bret Victor 的 Inventing on Principle 值得一看。

應用開發。當時 iOS 與 OS X 開發全數建立在 Objective-C 之上,而 Objective-C 語法冗長、門檻偏高。只要 Swift 能與既有框架維持順暢的互操作,大量開發者遷移過來幾乎是必然;簡潔的語法則會再吸引一批來自其他平台的新血。

上一次有大廠如此大張旗鼓地推出語言與平台,還是 2000 年微軟發表 C# 的時候。相隔約十五年,蘋果交出了 Swift——作為開發者,能見證一門語言的誕生,是件挺幸運的事。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved