我有几行工作代码:
let email = User.sharedInstance.emailAddress ?? ""
accountEmailAddress.text = email
Run Code Online (Sandbox Code Playgroud)
User.sharedInstance是User该类的非可选实例.它的emailAddress属性是可选的String?.accountEmailAddress是一个UILabel.
如果我尝试将其转换为单行代码:
accountEmailAddress.text = User.sharedInstance.emailAddress ?? ""
Run Code Online (Sandbox Code Playgroud)
我得到Swift编译器错误"模糊使用'??'".
我无法弄清楚在这里使用nil合并算子的含义是多么模糊.我想找出编译器为什么抱怨的原因,并且出于好奇,如果有办法让它成为一个干净的单线程.
(Xcode 6 beta 6.)
编辑:在操场上最小的复制:
// Playground - noun: a place where people can play
var foo: String?
var test: String?
// "Ambiguous use of '??'"
foo = test ?? "ValueIfNil"
Run Code Online (Sandbox Code Playgroud)
aka*_*kyy 21
我想这是因为它的可选性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?
Run Code Online (Sandbox Code Playgroud)
然而,编译器应该在这种情况下自动更喜欢非可选类型,因此我建议在此提交错误报告.
| 归档时间: |
|
| 查看次数: |
19063 次 |
| 最近记录: |