John
John

Reputation: 11

save the text in a text field as a variable

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?

Upvotes: 1

Views: 5688

Answers (2)

Raja Tamil
Raja Tamil

Reputation: 71

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 {

}

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

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)!

Upvotes: 1

Related Questions