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?

1

2 Answers 2

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)! 
Sign up to request clarification or add additional context in comments.

4 Comments

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 it may have nil IBoutlet , also i demonstrate other options
@Sh_Khan All of the code in your answer will crash if the outlet is nil.
@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.
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 {

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.