我试图在一个属性为可选的数组上使用 .sorted,但我得到了这个错误:
Ambiguous reference to member '+'
我不确定如何处理此处的可选项,并添加 !强制解包不起作用(我确定该数组在此代码运行时将具有值)。
let sortedoptions = decisions[selectedDecision].options.sorted(by: { $0.ratings.reduce(0, +) < $1.ratings.reduce(0, +) } )
和选项类:
struct Option: Codable {
var title: String
var ratings: [Int?]
}
有人知道怎么解决这个问题吗?
最佳答案
这可以通过以下方式解决
let sortedoptions = decisions[selectedDecision].options.sorted(by: { $0.ratings.reduce(0, {x,y in x + y!}) < $1.ratings.reduce(0, {x,y in x + y!})} )
这是因为错误提示无法对两个 Int?
执行加法类型。
此外,这是假设数组值永远不会为 nil
更安全的选择是替换 y!
通过 y ?? 0
关于arrays - Swift:在可选上使用 .sorted 时,对成员 '+' 的引用不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57438233/