struct Server: Codable {
let cats: Int
let dogs: Int
let fishies: Int
}
一定是
Codable
。
和
let x = Server(cats: 42, dogs: 13, fishes: 777)
有没有办法基本上做到这一点
print(x["dogs"])
与
print(x.dogs)
相同
和/或
x["fishes"] = 888
与
x.fishes = 888
相同。
(注意,我意识到你可以写一个愚蠢的扩展
if == "dogs" return .dogs
等。不需要建议这个。我想知道 Swift 现在提供什么,TY。)
有了
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)