NSTextField 通过使用 TextField 作为字典的名称来标注

NSTextField to Label by using TextField as the name of an dictionary

Swift4,Xcode9.3,Cocoa 应用程序。

如何将labelMain的字符串改成字典词, 用字符串键?

例如,用户在 TextField 中输入 "dict1", 该应用程序应该认识到它在 dict1 字典键“2”中, 并且标签应该打印出 "word2",而不是其他文字。

    let dict0 : Dictionary<String, String> = ["0" : "word0", "1" : "word1"]
    let dict1 : Dictionary<String, String> = ["2" : "word2", "3" : "word3"]

    labelMain.stringValue = TextField.stringValue["2"]

错误:无法使用 'String'

类型的索引下标 'String' 类型的值

创建一个将字典名称映射到实际字典的字典:

let dict0 : Dictionary<String, String> = ["0" : "word0", "1" : "word1"]
let dict1 : Dictionary<String, String> = ["2" : "word2", "3" : "word3"]
let dictMap = ["dict0": dict0, "dict1": dict1]

if let dict = dictMap[TextField.stringValue], let word = dict["2"] {
    labelMain.stringValue = word
}

或使用可选链接

if let word = dictMap[TextField.stringValue]?["2"] {
    labelMain.stringValue = word
}

或与 nil 合并运算符 结合使用以在找到 none 时提供默认值:

labelMain.stringValue = dictMap[TextField.stringValue]?["2"] ?? ""