1

I have been searching for an hour with no success so hope one of you will have pity. I am using Xcode 9 and Swift 4.

textIt.text = name

Works perfectly and I have used it in my app but

name = textIt.text

brings up the error code:

Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

All I want to do is to put some text from a variable into a field so the user can change it then I put the text back into the variable.

What am I doing wrong?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
John
  • 11
  • 1
  • 5

2 Answers2

1

In swift if a variable is optional and you want to set it to another you must use ! or ?? or If let You can try

let name =  textIt.text ?? ""

OR

 if let name =  textIt.text
 {
    print("name is : \(name)")
 }

OR but it may result in a crash if value is nil

 let name =  (textIt.text)!
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • 1
    None of this is needed. Simply do `let name = textIt.text!`. The `text` property is guaranteed never to return `nil`. It will return the empty string if there is no text. – rmaddy Feb 25 '18 at 19:09
  • @rmaddy it may have nil IBoutlet , also i demonstrate other options – Shehata Gamal Feb 25 '18 at 19:11
  • 1
    @Sh_Khan All of the code in your answer will crash if the outlet is `nil`. – rmaddy Feb 25 '18 at 19:11
  • 1
    @Sh_Khan Because the `text` property is optional so it needs to be unwrapped. But since it never actually returns `nil`, it is safe to force-unwrap. – rmaddy Feb 25 '18 at 19:58
1

You can track "name" variable when setting and getting textIt using something called Computer Property. This will allow you to tie your variable name and your text field.

var name:String? {

    get {
        return textIt.text
    }

    set {
        textIt.text = newValue
    }
}

When you set your name variable, textIt will automatically will be set. On the otherhand, when you get the name variable, i will get the value from textIt.

Since the name variable is optional you can use the following code to unwrap.

If let userName = name {

}

Raja Tamil
  • 71
  • 7