swift 使用变量访问元组的值

dkqlctbz  于 2022-11-21  发布在  Swift
关注(0)|答案(2)|浏览(106)

我如何从一个基于动态值的元组中读取一个项?例如,如果我想要“banana”,我可以这样做:

var tuple = ("banana", "sock", "shoe")
print(tuple.0)

但是如何使用存储在另一个变量中的值呢?

var parameter = 0

print(tuple.parameter)
6qqygrtg

6qqygrtg1#

元组不够灵活,无法做到这一点。您可以使用函数来接近:

let tuple = ("banana", "sock", "shoe")

let first = { (t: (String, String, String)) -> String in t.0 }
let second = { (t: (String, String, String)) -> String in t.1 }
let third = { (t: (String, String, String)) -> String in t.2 }

let choice = first
print(first(tuple))

但这根本无法扩展;您需要一组这样的函数来与 * 每个 * 元组类型进行交互。
一种选择是创建一个struct作为元组的替代,然后就可以使用KeyPath。例如:

struct Items
{
    let first: String
    let second: String
    let third: String

    init(tuple: (String, String, String))
    {
        self.first = tuple.0
        self.second = tuple.1
        self.third = tuple.2
    }
}

let choice = \Items.first

let items = Items(tuple: tuple)
print(items[keyPath: choice])

或者,如果元组都是同构的(就像示例中的一样),另一种选择是转换为数组并使用数组下标:

extension Array where Element == String
{
    init(_ tuple: (String, String, String))
    {
        self.init([tuple.0, tuple.1, tuple.2])
    }
}

let array = Array(tuple)
let index = 0
print(array[index])

(类似于下标的键路径也会出现在未来的Swift中,但在这种情况下,它们不会给你带来任何超出常规下标的东西。)

plicqrtu

plicqrtu2#

var parameter: KeyPath<(String, String, String), String> = \.0

print(tuple[keyPath: parameter])

相关问题