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

后端 未结 4 2161
别那么骄傲
别那么骄傲 2021-02-07 20:57

Previously in Swift 2.2 I\'m able to do:

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


        
4条回答
  •  我寻月下人不归
    2021-02-07 21:23

    Just extend the Collection or the Sequence

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

    edit/update:

    Xcode 10 • Swift 4 or later

    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
    

提交回复
热议问题