Swift 4.0 的新特性有哪些?


在本教程中,您將學習 Swift 4 中釋出了哪些更改。每次 Apple 釋出主要版本時,都會對 API 進行大量改進和新增。

Swift 4.0 中引入的新特性包括改進的關鍵路徑用於鍵值編碼、編碼和解碼、多行字串文字、字串是集合、改進的字典功能、單側範圍以及許多其他程式碼增強功能。

編碼和解碼

在 Swift 4.0 中,Apple 引入了 Codable 協議,使開發人員可以輕鬆進行編碼和解碼。您可以使用此協議在程式碼中實現序列化和反序列化。您可以對自定義資料型別進行編碼和解碼,而無需編寫太多程式碼。

您可以使用編碼將值儲存在屬性中,並且可以從自定義資料型別生成自定義 JSON。Swift 將自動編碼資料型別中的所有屬性 - 您無需執行任何操作。

多行字串文字

在 Swift 4.0 之前,您在字串中使用 \n 在需要時新增換行符。顯然,在字串中使用 /n 在程式碼中看起來不太合適。

在 Swift 4.0 中,Apple 透過簡化的多行字串文字語法解決了新增新行和在字串中使用雙引號的問題。它允許您自由新增換行符並使用三個雙引號和回車鍵。此後,根據需要開始使用任何變數、換行符和雙引號編寫字串。

示例

let professional = "🧑💻"
let introduction = """Swift language is most popular among iOS developer \(professional).
   Further....
   Swift is a fantastic way to write software, whether it’s for phones, desktops, servers, or anything else that runs code.

   It’s a safe, fast, and interactive programming language.
   """
print(introduction)

輸出

Swift language is most popular among iOS developer 🧑💻.

更多...

Swift 是一種編寫軟體的絕佳方法,無論它是用於手機、桌面電腦、伺服器還是任何其他執行程式碼的東西。

它是一種安全、快速且互動式的程式語言。

改進的鍵值編碼

Objective-C 的一個關鍵特性是它能夠獲取根物件名稱並動態向下鑽取任何屬性名稱,而不是使用簡單的字串文字指定物件鍵。這些引用(鍵路徑)強制進行編譯時檢查,以確保型別包含所需的鍵,從而消除了常見型別的執行時錯誤。

字典增強功能

Swift 4 為 Dictionary 和 Set 添加了新的強大功能。由於添加了一些實用程式方法,因此它們的使用更加愉快。

Swift 4 在字典上有一個 mapValues 方法來轉換所有值,並將它們使用原始鍵放回字典中。

現在可以使用字典並使用下標語法提供預設值,以避免以後必須解包可選值。

最後,Dictionary 的一個新新增是分組初始化器。這允許您透過根據您設定的任何條件對現有集合的序列進行分組來建立一個新字典。

增強的字串

在 Swift 4 中,對字串進行了許多改進,並且為字串型別添加了新的功能。讓我們看看其中的一些。

字串再次成為集合

字串再次成為集合,就像 Swift 2.0 之前一樣。此更改消除了對 String 上的 characters 陣列的需求。您現在可以直接迭代 String 物件

示例

在這裡,我們將展示如何在 Swift 4.0 中迭代字串的字元。

let stringValue = "Swift"
for char in stringValue {
   print(char)
}

輸出

S
w
i
f
t

在 Swift 4 之前,您使用 String 的 characters 陣列。但現在您可以像其他集合(如陣列)一樣直接迭代字串。

StringProtocol

此協議的所有功能都作為字串實現。在 Swift 4 中,Apple 添加了一種名為 Substring 的新型別來表示 String 的子序列。字串和子字串都符合 StringProtocol 並且行為幾乎相同。

示例

let sentence = "Swift language is great"
// How to make a subsequence?
let endIndex = sentence.index(sentence.startIndex, offsetBy: 4)
let languageName = sentence[sentence.startIndex...endIndex]

// print the substring and check the type of that string
print("Language name is: \(languageName) and it is type of: \(type(of: languageName))")

輸出

Language name is: Swift and it is type of: Substring

Unicode 9 的適配

在 Swift 4 之後,字串能夠正確解釋 Unicode 字元。

示例

print("👩💻".count) // Now: 1, Before: 2
print("👍🏽".count) // Now: 1, Before: 2
print("👨❤️💋👨".count) // Now: 1, Before: 4

輸出

2
1
4

單側範圍

Swift 採用了 Python 的單側範圍,其中缺少的側自動視為序列的開頭或結尾。我們無需擔心潛在的破壞,因為它與現有程式碼無關。

Swift 4 添加了使用單側範圍推斷開始和結束索引的功能。

示例

let planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
let firstPart = planets[..<4] // Before: planets[planets.startIndex..<4]
let secondPart = planets[4...] // Before: planets[4..<planets.endIndex]
print("First part: \(firstPart)")
print("Second part: \(secondPart)")

輸出

First part: ["Mercury", "Venus", "Earth", "Mars"]
Second part: ["Jupiter", "Saturn", "Uranus", "Neptune"]

Swift 包管理器中的更新

  • Swift 包管理器已經發生了很多變化。例如

  • 基於分支或提交雜湊查詢依賴項

  • 提供每個目標原始檔的位置

  • 可接受包的版本控制

  • 定義用於編譯的 Swift 版本

泛型下標

下標是使資料型別以直觀的方式可訪問的極其寶貴的一部分。為了提高它們的實用性,下標現在可以像以下這樣泛型

示例

struct GenericDictionary<Key: Hashable, Value> {
   private var data: [Key: Value]
   init(data: [Key: Value]) {
      self.data = data
   }
   subscript<T>(key: Key) -> T? {
      return data[key] as? T
   }
}
// creating a dictionary of type: [String: Any]
var earthData = GenericDictionary(data: ["name": "Pathik Patel", "score": 80])

// name will automaitcally infers return type without "as? String"
let name: String? = earthData["name"]
print("Name is: \(name ?? "") and type: \(type(of: name))")

// score will automatically infers return type without "as? Int"
let score: Int? = earthData["score"]
print("Score is: \(score ?? 0) and type: \(type(of: score))")

輸出

Name is: Pathik Patel and type: Optional<String>
Score is: 80 and type: Optional<Int>

結論

Swift 語言多年來確實發展壯大並日趨成熟。Swift 4 中的這些更改使我們能夠穩定地掌握 Swift 語言。最初,由於發生的重大更改,處理 Swift 程式碼庫很困難,但現在它更加穩定了。

嘗試在程式碼中使用大多數功能以在應用程式中編寫最佳化的程式碼。

更新於: 2023年1月5日

380 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.