<分区>
<分区>
我是 iOS 开发新手。我正在练习在 View 和 Controller 之间链接操作/ socket 。我的问题是我不知道为什么它会显示一些错误。你能看看我的代码并告诉我我缺少什么吗?
我收到以下错误:
Value of optional type 'String?' must be unwrapped to a value of type 'String'
Coalesce using '??' to provide a default when the optional value contains 'nil'
Force-unwrap using '!' to abort execution if the optional value contains 'nil'
代码如下:
@IBAction func submitAppointmentDetails(_ sender: Any) {
appointmentSetName.text = "Congratulations," + nameField.text + "You have now set up an appointment with us!"
}
正在发生的事情的照片:https://imgur.com/a/WKT4EyE
编辑:@matt这是一个不同的问题,因为您认为这是重复的线程没有我正在寻找的解决方案,但该线程中的两个人确实给了我解决方案。如果我只阅读您分享的主题,我永远不会找到解决方案。
最佳答案
nameField.text
类型为 String?
这意味着它是一个可选字符串(它可能包含 String
或 nil
)。 Swift 不允许您连接可选字符串。你必须打开这个值,你基本上已经有了 Swift 提出的问题中的方法:
您可以强制展开字符串 nameField.text!
.有了这个你告诉 Swift '从那个可选的字符串值,我确定它不是 nil
',但如果它是 nil
,这将使应用程序崩溃.
您可以使用合并运算符 ??
这样nameField.text ?? "<no_name>"
.这将执行以下操作:如果 nameField.text
不是 nil
, 那么文字就会正确显示;如果nameField.text
为零,"<no_name>"
将改为显示字符串。
关于ios - 可选类型 String 的值必须解包为 String 的值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56435408/