如何连接 SWIFT 中的可选字符串

How to concatenate optional String in SWIFT

我想连接一个字符串,我这样做了:

var text: String!
....
text = "hello" 
text += "! How r you?"

但是我得到了以下错误:

cannot convert value of type 'String!' to expected argument type 'inout String' text += "!" ^~~~

我该如何解决?谢谢

在你的例子中,将值声明为空是没有意义的,因为你要在下一行修改它。

但是,如果赋值发生在其他地方并且您想使用带有 ! 的变量,您应该检查字符串是否具有带有 ? 的值。如果 textnil.

,则不会调用此方法
text? += "! How r you?"

你必须定义没有感叹号的变量,像这样:

var text: String = ""
text = "hello" 
text += "! How r you?"

或更短的上下文函数:

var text: String = "hello" 
text += "! How r you?"

这样做就可以得到

var text = "Hello!" as! String
text = text + " How are you?"

希望对您有所帮助。

在处理 Swift 中的感叹号时,您必须记住,尝试使用 ! 访问不存在的可选值 会触发运行时错误

如果可选值有值,则认为“不等于nil”。所以你必须先检查一下才能访问它的基础值:

if text != nil {
    text += "! How are you?"
}