在Swift 3中扩展类型化数组(像Bool这样的原始类型)?
以前在Swift 2.2中我可以做到:
Previously in Swift 2.2 I'm able to do:
extension _ArrayType where Generator.Element == Bool{
var allTrue : Bool{
return !self.contains(false)
}
}
将[Bool]
扩展为.allTrue
.例如
[true, true, false].allTrue == false
但是在Swift 3.0中,我得到了这个错误:
But in Swift 3.0 I'm getting this error:
未声明的类型
_ArrayType
所以我尝试将其切换到Array
并使用新的关键字Iterator
So I tried switching it to Array
and using the new keyword Iterator
extension Array where Iterator.Element == Bool
var allTrue : Bool{
return !self.contains(false)
}
}
但是我遇到了另一个错误,抱怨我强迫元素是非泛型的
But I got a different error complaining that I'm forcing element to be non-generic
相同类型的要求使通用参数元素"变为非通用
Same-type requirement makes generic parameter 'Element' non-generic
我也在此 2岁的帖子中尝试了解决方案,但无济于事.
I've also tried the solutions in this 2 years old post but to no avail.
那么如何在Swift 3中扩展诸如Bool之类的基本类型的数组?
So how does one extend arrays of primitive types like Bool in Swift 3?
只需扩展Collection或Sequence
Just extend the Collection or the Sequence
extension Collection where Element == Bool {
var allTrue: Bool { return !contains(false) }
}
编辑/更新:
edit/update:
Xcode 10•Swift 4或更高版本
您可以使用Swift 4或更高版本的收集方法 allSatisfy
You can use Swift 4 or later collection method allSatisfy
let alltrue = [true, true,true, true,true, true].allSatisfy{$0} // true
let allfalse = [false, false,false, false,false, false].allSatisfy{!$0} // true
extension Collection where Element == Bool {
var allTrue: Bool { return allSatisfy{ $0 } }
var allFalse: Bool { return allSatisfy{ !$0 } }
}
测试场:
Testing Playground:
[true, true, true, true, true, true].allTrue // true
[false, false, false, false, false, false].allFalse // true