save the text in a text field as a variable

血红的双手。 提交于 2020-01-14 05:26:22

问题


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:


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



回答2:


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 {

}



来源:https://stackoverflow.com/questions/48976543/save-the-text-in-a-text-field-as-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!