以下是[通用版本]的情况:
let tuple: (first: Int, second: Int, third: Int) // tuple.0 is equivalent to tuple.first
enum TupleIndex: Int {
case first = 0, second, third
}
func selectTupleElement (index: TupleIndex) {
let indexNum = index.rawValue
let tupleElement = tuple.indexNum // Oh noooooo!!!
}
编译器将上面最后一行中指出的问题点读作“indexNum
属性或tuple
的元素”(当然不存在)而不是“元素索引tuple
等于indexNum
“
有没有办法按照元组做我正在尝试做的事情?
答案 0 :(得分:0)
你可以利用运行时内省来有条件地提取固定大小和相同类型成员的元组的n
:成员(例如下面的:为具有统一类型成员的arity 3的元组实现)和(有条件地)将其转换为成员的类型。 E.g:
func selectTupleElementFor<T>(memberNumber: Int, inTuple tuple: (T, T, T)) -> T? {
return Mirror(reflecting: tuple).children.enumerated()
.first(where: { $0.0 == memberNumber - 1 }).flatMap { $1.1 as? T }
}
// example usage
let tuple: (first: Int, second: Int, third: Int) = (10, 20, 30)
if let tupleMember = selectTupleElementFor(memberNumber: 2, inTuple: tuple) {
print(tupleMember) // 20
}
或者,使用您的TupleIndex
enum
:
enum TupleIndex: Int {
case first = 0, second, third
}
func selectTupleElementFor<T>(tupleIndex: TupleIndex, inTuple tuple: (T, T, T)) -> T? {
return Mirror(reflecting: tuple).children.enumerated()
.first(where: { $0.0 == tupleIndex.rawValue }).flatMap { $1.1 as? T }
}
// example usage
let tuple: (first: Int, second: Int, third: Int) = (10, 20, 30)
if let tupleMember = selectTupleElementFor(tupleIndex: .second, inTuple: tuple) {
print(tupleMember) // 20
}