SwiftUI:在“”之后插入从函数接收的字段名称。

SwiftUI Insert a field name received from a function following "."

提问人:baohoang 提问时间:11/13/2022 最后编辑:baohoang 更新时间:11/14/2022 访问量:72

问:

我从函数中获取字段名称。如何在点“”之后插入该字段名称。

struct User: Identifiable {
        let username: String
        let fullName: String
        var description: String = ""
    }
  1. 从标题中获取字段名称
extension User {
    func get_field_name(key: String?) -> String {
        var default_field = ""
        guard let key = key else { return default_field }
        let field: [String: String] = [
            "Name" : "fullName",
            "Username" : "username",
            "Bio" : "description"
        ]
        return field[key] ?? default_field
    }
}
  1. 期望。

例如,如果“item.title”是“Name”,则

let user: User
Text(item.title) //OK - Name
Text(user.get_field_name(key: item.title)) //OK - fullName
Text(user.???) //??? How to insert field name following "."
  1. 目的

我在下面的图片中使用它

enter image description here

非常感谢您的回答。

swift swiftui 插入 func

评论

1赞 Joakim Danielson 11/13/2022
我不明白你想用最后一个文本示例做什么。它应该在视图中显示什么?您的意思是要显示用户对象中该字段的值吗?
0赞 baohoang 11/13/2022
完全@JoakimDanielson
0赞 Joakim Danielson 11/13/2022
那么我相信你有下面的答案。
0赞 baohoang 11/13/2022
是的。感谢您对我的问题的关注@JoakimDanielson

答:

1赞 Sweeper 11/13/2022 #1

我认为您正在寻找关键路径。

更改为:get_field_name

func getUserKeyPath(key: String?) -> KeyPath<User, String>? {
    guard let key = key else { return nil }
    let field: [_: KeyPath<User, _>] = [
        "Name" : \.fullName,
        "Username" : \.username,
        "Bio" : \.description
    ]
    return field[key]
}

然后你可以做:

if let keyPath = getFieldKeyPath(key: item.title) {
    Text(user[keyPath: keyPath])
} else {
    // handle the case when item.title does not match any property name in User
}

如果要在 when does not match any property name 中显示默认字符串,也可以在单个表达式中执行此操作:Textitem.title

Text(getFieldKeyPath(key: "Name").map { user[keyPath: $0] } ?? "Unknown")