Swift String Interpolation displaying optional?

我是研究僧i 提交于 2019-11-27 03:55:05

问题


When i use the following code and have nameTextField be "Jeffrey" (or any other name)

@IBAction func helloWorldAction(nameTextField: UITextField) {

    nameLabel.text = "Hello, \(nameTextField.text)"

}

nameLabel displays... Hello, Optional("Jeffrey")

But, when I change the previous code to include a "!" like this:

@IBAction func helloWorldAction(nameTextField: UITextField) {

    nameLabel.text = "Hello, \(nameTextField.text!)"

}

The code works as expected and nameLabel displays.... Hello, Jeffrey

Why is the "!" required, in the video tutorial I used to create this simple program he did not use the "!" and the program worked as expected.


回答1:


Optionals must be unwrapped. You must check for it or force unwrap as you do. Imagine the optional as a box where you put a value. Before you can access it, you need to put it out.

if let name = nameTextField.text {
    nameLabel.text = "Hello, \(name)"
}



回答2:


Another alternative is to use the null coalescing operator within the interpolated string for prettier text without the need for if let.

nameLabel.text = "Hello, \(nameTextField.text ?? "")"

It's less readable in this case, but if there were a lot of strings it might be preferable.




回答3:


Here's a handy extension to unwrap Any? to String.

Set a default value for nil values.

extension String {
    init(_ any: Any?) {
        self = any == nil ? "My Default Value" : "\(any!)"
    }
}

// Example

let count: Int? = 3
let index: Int? = nil
String(count)
String(index)

// Output
// 3
// My Default Value


来源:https://stackoverflow.com/questions/31417853/swift-string-interpolation-displaying-optional

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