gpt4 book ai didi

Swift:使用变量/参数访问元组元素?

转载 作者:行者123 更新时间:2023-11-30 12:44:09 25 4
gpt4 key购买 nike

这是[通用版本]情况:

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!!!
}

编译器将上面最后一行所示的问题点读取为“indexNumtuple 属性或元素”(当然不存在),而不是“tuple 的元素”索引等于 indexNum "

有没有办法使用元组来做我想做的事情?

最佳答案

可以利用运行时自省(introspection)来有条件地提取固定大小和相同类型成员的元组中的第n个成员 (例如下面:为具有统一类型成员的 arity 3 元组实现)并(有条件地)将其转换为成员的类型。例如:

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
}

关于Swift:使用变量/参数访问元组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41852812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com