在Swift 3中扩展类型化数组(像Bool这样的原始类型)? [英] Extending typed Arrays (of primitive types like Bool) in Swift 3?

查看:180
本文介绍了在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

这篇关于在Swift 3中扩展类型化数组(像Bool这样的原始类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆