简体   繁体   English

SwiftUI 在“.”后面插入一个从 function 收到的字段名称。

[英]SwiftUI Insert a field name received from a function following "."

I get a field name from a function. How to insert that field name following dot "."我从 function 得到一个字段名。如何在点“.”之后插入该字段名。

  1. Model Model
struct User: Identifiable {
        let username: String
        let fullName: String
        var description: String = ""
    }
  1. Get a field name from a title从标题中获取字段名称
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. Expect.预计。

Example if "item.title" is "Name" then例如,如果“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. Purpose目的

I use it in the pic below我在下面的图片中使用它

在此处输入图像描述

Thank you so much for your answer.非常感谢您的回答。

I think you are looking for key paths.我认为您正在寻找关键路径。

Change get_field_name to: 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]
}

Then you can do:然后你可以这样做:

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
}

You can also do this in a single expression if you want to show a default string in the Text when item.title does not match any property name:如果您想在item.title与任何属性名称不匹配时在Text中显示默认字符串,您也可以在单个表达式中执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM