swift4.2新特性
CaseInterable
协议
在4.2之前我们想打印枚举里面所有的case只能自己通过以下方式去实现:
/// swift4.2之前,错误示例
enum Gait {
case walk
case trot
case canter
case gallop
static var allCases: [Gait] = [.walk, .trot, .canter, .gallop]
}
for gait in Gait.allCases {
print(gait)
}
这样每次新增和删除一个case都要去维护allCases这个数组,这样造成了诸多不便,在Swift 4.2
中新增了CaseIterable
协议,通过遵循这个协议,会自动生成allCases
,例如:
enum Gait: CaseIterable {
case walk
case trot
case canter
case gallop
case jog
}
for gait in Gait.allCases {
print(gait)
}
这样我们就不用去自己维护allCases
这个集合了
条件一致性
条件一致性是在Swift 4.1
引入的,例如在Swift 4.0
的时候下面代码运行会报错:
let animals = ["cat", "dog", "weasel"]
animals.contains("dog") // OK
let coins = [[1, 2], [3, 6], [4, 12]]
/// Error because the element type [Int] is not equatable
coins.contains([3, 6])
然而在Swift 4.1
之后类似这种的问题得到了解决:
extension Array: Equatable where Element: Equatable {
static func ==(lhs: Array<Element>, rhs: Array<Element>) -> Bool {
let count = lhs.count
if count != rhs.count { return false } for x in 0..<count {
if lhs[x] != rhs[x] { return false } }
return true
}
}
let coins = [[1, 2], [3, 6], [4, 12]]
coins.contains([3, 6]) // This now works!
<