Swift String Interpolation displaying optional?

二次信任 提交于 2019-11-28 10:57:14

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)"
}

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.

Addy

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