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 中,对字符串进行了许多改进,并且为字符串类型添加了新的功能。让我们看看其中的一些。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
字符串再次成为集合
字符串再次成为集合,就像 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 代码库很困难,但现在它更加稳定了。
尝试在代码中使用大多数功能以在应用程序中编写优化的代码。