ios - 可选类型 String 的值必须解包为 String 的值类型?

标签 ios swift

<分区>

我是 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?这意味着它是一个可选字符串(它可能包含 Stringnil )。 Swift 不允许您连接可选字符串。你必须打开这个值,你基本上已经有了 Swift 提出的问题中的方法:

  1. 您可以强制展开字符串 nameField.text! .有了这个你告诉 Swift '从那个可选的字符串值,我确定它不是 nil ',但如果它是 nil,这将使应用程序崩溃.

  2. 您可以使用合并运算符 ??这样nameField.text ?? "<no_name>" .这将执行以下操作:如果 nameField.text不是 nil , 那么文字就会正确显示;如果nameField.text为零,"<no_name>"将改为显示字符串。

关于ios - 可选类型 String 的值必须解包为 String 的值类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56435408/

上一篇:ios - 如何查看订阅是否已取消?

下一篇:ios - 在 Windows 上启动项目,现在在 Mac 上克隆使 iOS Bundle Options 选项卡消失

相关文章:

swift - 每天激活一个查看周数的功能

ios - Xcode 10.2,Swift 5,使用 Release Scheme 构建程序时命令 compileSwift 失败

swift - 将 SwiftyJSON 映射到数组

ios - 向右滑动即可关闭 ViewController,无需使用 Storyboard Swift

ios - 将JSON映射为数组或对象

ios - 在 SpriteBuilder 中使对象出现在第 N 帧而不是第 0 帧

ios - 如何以编程方式打开 .xcodeproj?

ios - UIView 中的 UITableView

swift - 在 iOS 9 中遇到 WKWebview 和 UIWebView 的问题

ios - 旋转时自动更新 preferredContentSize