吖奇说*_*HUō 12 arrays extension-methods swift swift3
以前在Swift 2.2中我能做到:
extension _ArrayType where Generator.Element == Bool{
var allTrue : Bool{
return !self.contains(false)
}
}
Run Code Online (Sandbox Code Playgroud)
[Bool]随着延伸.allTrue.例如
[true, true, false].allTrue == false
Run Code Online (Sandbox Code Playgroud)
但是在Swift 3.0中我遇到了这个错误:
未申报的类型
_ArrayType
所以我尝试将其切换为Array使用new关键字Iterator
extension Array where Iterator.Element == Bool
var allTrue : Bool{
return !self.contains(false)
}
}
Run Code Online (Sandbox Code Playgroud)
但我有一个不同的错误抱怨我强迫元素是非泛型的
相同类型的要求使通用参数'Element'非通用
我也在这个2年的帖子中尝试了解决方案,但无济于事.
那么如何在Swift 3中扩展原始类型的数组,如Bool?
Leo*_*bus 10
只需扩展Collection或Sequence
extension Collection where Element == Bool {
var allTrue: Bool { return !contains(false) }
}
Run Code Online (Sandbox Code Playgroud)
测试游乐场:
let alltrue = [true, true,true, true,true, true].allSatisfy{$0} // true
let allfalse = [false, false,false, false,false, false].allSatisfy{!$0} // true
Run Code Online (Sandbox Code Playgroud)
另一个选择是创建自定义协议并扩展它:
extension Collection where Element == Bool {
var allTrue: Bool { return allSatisfy{ $0 } }
var allFalse: Bool { return allSatisfy{ !$0 } }
}
Run Code Online (Sandbox Code Playgroud)
小智 8
Apple 在Swift 3.0中取代_ArrayType了_ArrayProtocol(参见GitHub上Apple的Swift源代码),所以你可以通过以下方式做同样的事情:在Swift 2.2中做的事情:
extension _ArrayProtocol where Iterator.Element == Bool {
var allTrue : Bool { return !self.contains(false) }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
964 次 |
| 最近记录: |