Reputation: 408
I'm trying to reference the text of a UITextField
so I can use it in different places within my app.
@IBOutlet weak var mealNameUITextField: UITextField!
@IBAction func nextButton(sender: AnyObject) {
mealNameBeingCreated = String(mealNameUITextField.text)
print(mealNameBeingCreated)
}
It's giving me the error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Can anyone tell me the correct way to reference the text? Also, it might be good to mention I want to use this info in a global variable.
Upvotes: 1
Views: 885
Reputation: 11
@IBAction func nextButton(sender: AnyObject) {
let mealNameBeingCreated:String = self.mealNameUITextfield.text!
print(mealNameBeingCreated)
}
OR
@IBAction func nextButton(sender: AnyObject) {
let mealNameBeingCreated = self.mealNameUITextfield.text!
print(mealNameBeingCreated)
}
The value returned by the textfield is an optional and we have to unwrap it using "!" symbol
The syntax depends on the version of the Swift language you are working on. I am using XCode 7.2 which supports swift 2.1.1
Upvotes: 1
Reputation: 9346
Just write like this:
@IBAction func nextButton(sender: AnyObject) {
let mealNameBeingCreated : String = mealNameUITextField.text!
print(mealNameBeingCreated)
}
Upvotes: 2