Swift 5.7,您可以使用字符串来动态地使用带有 Structs 的 keyPath 吗?

问题描述 投票:0回答:1
struct Server: Codable {
 let cats: Int
 let dogs: Int
 let fishies: Int
}

一定是

Codable

let x = Server(cats: 42, dogs: 13, fishes: 777)

我们可以使用键路径:

print( x[keyPath: \.dogs] )

这会打印“13”。

有没有办法使用字符串作为键路径?所以,类似

let str = ".dogs"
print( x[ keyPath: \$str ] ]

或者也许

let s = ".dogs"
let k = KeyPath(fromString: s)
print( x[keyPath: k] )

(注意,我很欣赏还有许多其他方法,例如使用sql、字典、switch 语句等。手头的问题如前所述,TY)

swift codable swift-structs
1个回答
1
投票

有了

struct
,你就有了
KeyPath
WritableKeyPath
。正如所写,您的
Server
仅与
KeyPath
兼容,因为您的所有属性都是
let

print(x[keyPath: \.dogs])

如果您更改属性以使它们可变

var
您可以使用。

struct Server: Codable {
    var cats: Int
    var dogs: Int
    var fishies: Int
}

var x = Server(cats: 42, dogs: 13, fishies: 777)

print(x[keyPath: \.dogs])

x[keyPath: \.fishies] = 888

print(x)
© www.soinside.com 2019 - 2024. All rights reserved.