这里来讲讲 Swift 4.2 中都更新了哪些内容, 参考的原文链接在这里.

Swift 4.2 中的更新内容部分介绍

下面是 Swift 4.2 中的更新内容部分介绍, 主要是抽取目前开发过程中经常会使用到的讲, 完整内容请访问这个链接.

  1. 现在可以对 weakself 使用可选绑定了, 比如在闭包中使用 [weak self] 进行了声明, 则可以这样:
swift
if let self = self {
  //...
}

而无需像以前那样再去取一个 strongSelf 之类的名字了.

  1. 新增一个 #warning 预处理指令, 实现类似 // TODO: 的效果, 这样无需额外脚本就可以显示警告信息了.

  2. enum 类型新增了一个 CaseIterable 协议, 所有的 enum 默认都实现了这个协议, 其作用是将 enum 中所有的 case 都列出来:

swift
enum CompassDirection: CaseIterable {
  case north, south, east, west
}

print("There are \(CompassDirection.allCases.count) directions.")
  1. 新增了若干随机数生成方法, 以替代之前使用的 arc4random_uniform(实际上是一种统一的随机 API, 详见这个文档):
swift
Int.random(in: 1..<5)	// 生成某个范围内的随机数
Bool.random()			// 随机布尔值
let shuffledNumbers = [0, 1, 2, 3, 4].shuffled()	// 对 array 乱序
let bingoNumbers = [0, 1, 2, 3, 4, 5]
bingoNumbers.randomElement()	// 在 array 中随机取元素
  1. 针对泛型的优化升级, 现在可以像下面这样写泛型扩展时候的条件了:
swift
extension Array: Equatable where Element: Equatable {
  static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool { ... }
}
  1. 在标准库的集合类型上新增按条件来 removeAll 的方法:
swift
nums.removeAll(where: isOdd)
  1. 在标准库的集合类型上新增 allSatisfy 方法, 以判断某个集合的所有元素是否都满足给定条件:
swift
nums.allSatisfy(isOdd)
  1. 另外对 Hashable 做了许多改进, 详见这个链接.

  2. 在集合类型上新增如下方法:

swift
let a = [20, 30, 10, 40, 20, 30, 10, 40, 20]
a.last(where: { $0 > 25 })          // 40
a.lastIndex(where: { $0 > 25 })     // 7
a.lastIndex(of: 10)                 // 6
  1. 在布尔类型上新增 toggle 方法, 方法实现如下所示, 功能就是对布尔值进行开关:
swift
extension Bool {
  /// Equivalent to `someBool = !someBool`
  ///
  /// Useful when operating on long chains:
  ///
  ///    myVar.prop1.prop2.enabled.toggle()
  mutating func toggle() {
    self = !self
  }
}
  1. Swift 4.2 上, 语言的 ABI 稳定又进了一步.

  2. 新增针对编译器版本的预处理指令:

swift
#if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))
// Code targeting the Swift 4.1 compiler and above.
#endif

#if swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))
// Code targeting the Swift 4.2 compiler and above.
#endif

#if swift(>=5.0) || (swift(>=4.1.50) && !swift(>=4.2)) || (swift(>=3.5) && !swift(>=4.0))
// Code targeting the Swift 5.0 compiler and above.
#endif

Xcode 10 更新内容部分介绍

  1. 代码折叠终于回来了…普天同庆

  2. 在 Debug 模式下, 增量编译现在是默认选项了(在 Compilation Mode 设置中).

  3. 单元测试的性能得到了提升.

  4. 其他的待探索…