The first thing you want to do is set up a dictionary with all of the pairs you want, for example:
//Put this line outside of viewDidLoad
var dictionary: [String: String] = [:]
//Put these lines inside of viewDidLoad
dictionary["Italy"] = ""
dictionary["Mexico"] = ""
//...Add more pairs to the dictionary
Now that you have defined all of your pairs, the next thing you want to do is setup the delegate of your text field. Doing this allows you to run some block of code whenever text is entered into your textfield. First, in your view controllers class definition, you want to conform to the UITextFieldDelegate:
class ViewController: UIViewController, UITextFieldDelegate {
//...rest of the code in the view controller
}
Then, in your viewDidLoad, you want to set the delegate of your text field to self (a.k.a. to this view controller, which we have just conformed to the UITextFieldDelegate):
override func viewDidLoad() {
super.viewDidLoad()
//...rest of code in viewDidLoad
myTestField.delegate = self
}
Now, with all of that out of the way, we want to call this function, just start typing textfield and it will autocomplete because we have already conformed to the UITextFieldDelegate:
func textFieldDidEndEditing(_ textField: UITextField) {
//...This function is called EVERY time editing is finished in myTestField
}
Ok, so inside of the textFieldDidEndEditing function, all we need to do is check what was entered in myTestField and see if it matches any of the keys in the dictionary we created in the first step...if it does, then we are finally going to update our label:
func updateLabel(textField: UITextField) {
//we are using guard here because we are dealing with optional values,
//meaning that textField.text doesn't necessarily have a value, and
//dictionary[text] may not actually have a value either.
guard let text = textField.text,
let labelText = dictionary[text] else {return}
//Now we are going to actually update our label
emojiLabel.text = labelText
}
Ok, looking good, last thing to do is just call our updateLabel function inside of the textFieldDidEndEditing function:
func textFieldDidEndEditing(_ textField: UITextField) {
//...This function is called EVERY time editing is finished in myTestField
updateLabel(textField: textField)
}
That's it!