Swift4, Xcode9.3, Cocoa App.
How to change the string of labelMain to a dictionary word, with a string key?
for example, a user put in "dict1" in the TextField, the app should recognized that it is in the dict1 dictionary key "2", and the label should print out "word2", instead of other words.
let dict0 : Dictionary<String, String> = ["0" : "word0", "1" : "word1"]
let dict1 : Dictionary<String, String> = ["2" : "word2", "3" : "word3"]
labelMain.stringValue = TextField.stringValue["2"]
error: Cannot subscript a value of type 'String' with an index of type 'String'
Create a dictionary that maps dictionary names to the actual dictionary:
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
}
or using optional chaining:
if let word = dictMap[TextField.stringValue]?["2"] {
labelMain.stringValue = word
}
or combined with the nil coalescing operator to provide a default value if none was found:
labelMain.stringValue = dictMap[TextField.stringValue]?["2"] ?? ""