0

I just want to get value from input and show them in textfield. I am a newbie so please tell me why ?

@IBOutlet weak var inputName: UITextField!
@IBOutlet weak var inputEmail: UITextField!
@IBOutlet weak var inputPhone: UITextField!
@IBOutlet weak var outResult: UITextView!


@IBAction func act_Btn(sender: AnyObject) {
    let name = inputName.text
    let email = inputEmail.text
    let phone = inputPhone.text

    let outResultValue = "Name : \(name) \nEmail : \(email) \nPhone : \(phone)"

    outResult.text = outResultValue
}

But, why have prefix text "Optional" in my result ?

enter image description here

Ryan Tran
  • 467
  • 6
  • 16

2 Answers2

1

You just need to put the ! to get rid of Optional value. The reason is textField.text is may be nil.

@IBAction func act_Btn(sender: AnyObject) {
    let name = inputName.text!
    let email = inputEmail.text!
    let phone = inputPhone.text!

    let outResultValue = "Name : \(name) \nEmail : \(email) \nPhone : \(phone)"

    outResult.text = outResultValue
}

Also take a look at some examples:

What the difference between using or not using "!" in Swift?

Difference between optional values in swift?

Community
  • 1
  • 1
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
0

[...] optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with an if statement to see if a value exists, and can be conditionally unwrapped with optional binding to access the optional’s value if it does exist.

Sometimes it’s clear from a program’s structure that an optional will always have a value, after that value is first set. In these cases, it’s useful to remove the need to check and unwrap the optional’s value every time it’s accessed, because it can be safely assumed to have a value all of the time.

These kinds of optionals are defined as implicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.

Implicitly unwrapped optionals are useful when an optional’s value is confirmed to exist immediately after the optional is first defined and can definitely be assumed to exist at every point thereafter. The primary use of implicitly unwrapped optionals in Swift is during class initialization [...]

For more details, read this.

Pang
  • 9,564
  • 146
  • 81
  • 122
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56