nyan nyan nyan nyan nyan nyan - 1 year ago 131
Swift Question

Extending typed Arrays (of primitive types like Bool) in Swift 3?

Previously in Swift 2.2 I'm able to do:

extension _ArrayType where Generator.Element == Bool{
var allTrue : Bool{
return !self.contains(false)

which extends
. E.g.

[true, true, false].allTrue == false

But in Swift 3.0 I'm getting this error:

undeclared type

So I tried switching it to
and using the new keyword

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

I've also tried the solutions in this 2 years old post but to no avail.

So how does one extend arrays of primitive types like Bool in Swift 3?

Answer Source

Just extend the Collection or the Sequence

extension Collection where Iterator.Element == Bool { 
    var allTrue: Bool { return !contains(false) }

Testing Playground:

[true, true,true, true,true, true].allTrue // true
[true, true,false, true,true, true].allTrue // false

Another option is to create a custom protocol and extend it:

protocol BoolConvertible {
    var bool: Bool { get }
extension Bool: BoolConvertible {
    var bool: Bool { return self }

extension Array where Element: BoolConvertible {
    var allTrue: Bool { return !contains{!$0.bool} }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download