gpt4 book ai didi

swift - "??"的使用不明确

转载 作者:IT王子 更新时间:2023-10-29 05:26:03 25 4
gpt4 key购买 nike

我有几行工作代码:

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

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

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

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

我收到 Swift 编译器错误“'??' 的使用不明确”。

我不太明白这里使用 nil 合并运算符有什么歧义。我正在寻找编译器提示的原因,并且出于好奇,是否有办法让它成为一个干净的单行代码。

(Xcode 6 测试版 6。)

编辑: Playground 上的最小复制:

// 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 接受 StringString?,编译器无法决定使用哪个重载,因此会引发错误。

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

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?

尽管如此,在这种情况下,编译器应该自动优先选择非可选类型,因此我建议就此提交错误报告。

关于swift - "??"的使用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25620128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com