Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Aditya Pandey
Aditya Pandey
7,210 Points

error in my code

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var textField: UITextField!

let capitals  = ["India" : "New Delhi",
                         "China" : "Beijing",
                         "Russia" : "Moscow",
                         "Brazil" : "Brasilia"]

override func viewDidLoad() {
    super.viewDidLoad()

    self.textField.delegate = self
    textField.becomeFirstResponder()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

func textFieldDidEndEditing(_ textField: UITextField) {

    let key = String(describing: self.textField.text)
    print(capitals[key])

}

}

This is my code and when I type "China" in the text field, it prints nil in the console.

1 Answer

Ian Billings
PLUS
Ian Billings
Courses Plus Student 7,494 Points

Hi,

The issue is the textField.text is an optional String, so you need to unwrap it first, before passing it to the String(description:) initialiser.

E.g.

func textFieldDidEndEditing(_ textField: UITextField) {
    if let text = self.textField.text {
        let key = String(describing: text)
        print(capitals[key])
   }
}
Aditya Pandey
Aditya Pandey
7,210 Points

Thanks that solved the problem!