[英]Extending typed Arrays (of primitive types like Bool) in Swift 3?
以前在Swift 2.2中我能做到:
extension _ArrayType where Generator.Element == Bool{
var allTrue : Bool{
return !self.contains(false)
}
}
它使用.allTrue
擴展[Bool]
。 例如
[true, true, false].allTrue == false
但是在Swift 3.0中我遇到了這個錯誤:
未聲明的類型
_ArrayType
所以我嘗試將其切換到Array
並使用新的關鍵字Iterator
extension Array where Iterator.Element == Bool
var allTrue : Bool{
return !self.contains(false)
}
}
但我有一個不同的錯誤抱怨我強迫元素是非泛型的
相同類型的要求使通用參數'Element'非通用
我也在這個2年的帖子中嘗試了解決方案,但無濟於事。
那么如何在Swift 3中擴展原始類型的數組,如Bool?
只需擴展Collection或Sequence
extension Collection where Element == Bool {
var allTrue: Bool { return !contains(false) }
}
編輯/更新:
Xcode 10•Swift 4或更高版本
您可以使用Swift 4或更高版本的收集方法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 } }
}
測試游樂場:
[true, true, true, true, true, true].allTrue // true
[false, false, false, false, false, false].allFalse // true
蘋果取代_ArrayType
與_ArrayProtocol
在雨燕3.0( 見GitHub上蘋果的斯威夫特源代碼 ),這樣你可以做你的雨燕2.2通過執行以下操作做了同樣的事情:
extension _ArrayProtocol where Iterator.Element == Bool {
var allTrue : Bool { return !self.contains(false) }
}
從Swift 3.1(包含在Xcode 8.3中)開始,您現在可以使用具體約束擴展類型 :
extension Array where Element == Bool {
var allTrue: Bool {
return !contains(false)
}
}
您也可以擴展Collection
而不是Array
,但是您需要約束Iterator.Element
,而不僅僅是Element
。
擴展_ArrayProtocol
或Collection
對我來說不起作用,但是Sequence
確實如此。
public extension Sequence where Iterator.Element == String
{
var allTrue: Bool { return !contains(false)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.