![](/img/trans.png)
[英]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.