Swift 5.7,有没有办法将 keyPaths 与 Structs 一起使用?

问题描述 投票: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["dogs"])

print(x.dogs)

相同

和/或

x["fishes"] = 888

x.fishes = 888
相同。


(注意,我意识到你可以写一个愚蠢的扩展

if == "dogs" return .dogs
等。不需要建议这个。我想知道 Swift 现在提供什么,TY。)

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

有了

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.