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?

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...