在 guard let 或 if let 多重解包中让元素强制可空
我非常喜欢在 // 装作这个函数执行了某些复杂的操作 func someArray() -> [Int]? { return [1,2,3,4,5,6] } func example() { guard let array = someArray(),numberThree = array[2] where numberThree == 3 else { return } print(numberThree) } 这会出现问题。编译器会告诉您,这里需要是一个可空值:
因此,为了解决这个问题,最后往往是这样子结束的: func example() { guard let array = someArray() else { return } let numberThree = array[2] guard numberThree == 3 else { return } print(numberThree) } 这不仅看起来十分丑陋,并且您还必须要写两次失败处理闭包 (failure block) 代码。当然,因为这是一个简单的例子,我们只用写 所以,有没有什么好的解决方案呢?好吧,由于 func example() { guard let array = someArray(),numberThree = Optional.Some(array[2]) where numberThree == 3 else { return } print(numberThree) } 您可能记得,Swift 的可空值的内部是一个包含 这可能会带来一点小小的开销,但另一方面,它允许我们让 很显然,这不仅能对诸如 guard let aString = optionalString(),elements = Optional.Some(aString.characters.split("/")),last = elements.last,count = Optional.Some(last.characters.count),where count == 5 else { fatalError("Wrong Path") } print("We have (count) items in (last)")
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |