swift4.2新特性

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!
<
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值