[英]How to find the index of a tuple element from an tuple array? iOS, Swift
[英]Extend Array constrained when Element is a tuple
當元素是一種元組時,有沒有辦法擴展數組?
public extension Array where Element: (timeZoneName: String, formattedName: String){
}
該聲明返回4個錯誤:
- 語句不能以閉包表達式開頭
- 支撐塊語句是未使用的閉包
- 期待'{'的延伸
- 類型名稱的預期標識符
我不知道所顯示的錯誤是否准確。 有任何想法嗎?
Swift 3版appzYourLife的回答:
extension Sequence where Iterator.Element == Tuple2 {
func foo() {}
}
由於(AFAIK) Tuple
類型不符合Protocol
(甚至沒有名稱),因此很難做到你需要的東西。
這是我能得到的最接近的(也許其他人可以提供更優雅的解決方案)。
首先,我們定義幾種類型
typealias Tuple2 = (Any, Any)
typealias Tuple3 = (Any, Any, Any)
是的,一些讀者現在明白我要去哪里,可能不喜歡它......
我也不喜歡它
現在讓我們擴展協議SequenceType
,當序列的Element
是Tuple2
時添加foo
方法...
extension SequenceType where Generator.Element == Tuple2 {
func foo() {}
}
或者Tuple3
extension SequenceType where Generator.Element == Tuple3 {
func foo() {}
}
接下來,我們定義並填充Tuple2
數組
let list: [Tuple2] = [(1,2)]
現在擴展已應用,我們可以編寫
list.foo()
僅當數組顯式聲明為[Tuple2]
(或[Tuple3]
)時, [Tuple3]
。
像這樣的東西不起作用
let list = [(1,2)]
list.foo() // compile error
它現在可以在Swift 3.1中使用。
extension Array where Element == (String, String) {
...
}
您不能添加特定類型,例如extension Array where Element == Int
因為這會將通用Array轉換為非泛型版本。
您將看到類似於same-type requirement makes generic parameter 'Element' non-generic
的錯誤, same-type requirement makes generic parameter 'Element' non-generic
編輯
它確實看起來合法(至少在Swift 2.2中):
\ntypealias tzTuple =(timeZoneName:String,formattedName:String)\n\nextension Array其中Element:tzTuple {\n\n}\n
您將不得不看看它是否在運行時工作。
我在Playground中檢查這個,目前,Playgrounds還沒有完全適用於Swift 2.2-dev
我會建議這樣做:
typealias tzTuple = (timeZoneName: String, formattedName: String) extension Array { func formattedName(index: Int) -> String? { if self[index] is tzTuple { return (self[index] as! tzTuple).formattedName } return nil } }
會允許你這樣做
let foo = [(timezoneName: "PST", formattedName: "Pacific Standard Time"),(timezoneName: "AEST", formattedName: "Australian Eastern Time")] print(foo.formattedName(0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.