微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 模糊使用“??”

我有几行工作代码
let email = User.sharedInstance.emailAddress ?? ""
    accountEmailAddress.text = email

User.sharedInstance是User类的非可选实例.它的emailAddress属性是可选的String? accountEmailAddress是一个UILabel.

如果我尝试把它变成一行代码

accountEmailAddress.text = User.sharedInstance.emailAddress ?? ""

我得到Swift编译器错误“模糊使用’??’”.

我不清楚在这里使用无合并运算符的含义是什么.我正在寻找为什么编译器的抱怨,出于好奇,如果有一种方法使它成为一个干净的一线.

(Xcode 6 beta 6)

编辑:操场上最小的复制:

// Playground - noun: a place where people can play
var foo: String?
var test: String?

// "Ambiguous use of '??'"
foo = test ?? "ValueIfNil"
我猜这是因为UILabel.text的可选性.操作符?有2个重载 – 一个返回T,另一个返回T?

由于UILabel.text同时接受String和String?,编译器无法决定使用哪个重载,因此会引发错误.

您可以通过严格指定结果类型来修复此错误

String(User.sharedInstance.emailAddress ?? "")

(User.sharedInstance.emailAddress ?? "") as String

// or,when String! will become String? in the next beta/gm

(User.sharedInstance.emailAddress ?? "") as String?

然而,在这种情况下,编译器应该自动地喜欢非可选类型,因此我建议在此提交错误报告.

原文地址:https://www.jb51.cc/swift/319524.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐