在 SwiftUI 中,我想在字典中存储一些键值对数据。我可以将字典中的项目绑定到 TextField 或其他需要绑定的地方吗?
我想做这样的事情:
@State var myDic: [String : String] = [
"name": "Tim"
"company": "Apple"
]
TextField("Name", text: $myDic["name"] ?? "")
行为所在:
我会创建一个自定义
Dictionary
下标。
extension Dictionary where Value == String {
subscript(emptyStringAsNil key: Key) -> Value {
get { self[key] ?? "" }
set { self[key] = newValue.isEmpty ? nil : newValue }
}
}
用途:
TextField("Foo", text: $myDic[emptyStringAsNil: "name"])