Swift:在可选上使用 .sorted 时对成员“+”的引用不明确
Swift: Ambiguous reference to member '+' when using .sorted on optional
我正在尝试对一个属性为可选的数组使用 .sorted,但出现此错误:
Ambiguous reference to member '+'
我不确定如何处理此处的可选项,并添加 !强制解包不起作用(我确定该数组在此代码运行时将具有值)。
let sortedoptions = decisions[selectedDecision].options.sorted(by: { [=11=].ratings.reduce(0, +) < .ratings.reduce(0, +) } )
和选项class:
struct Option: Codable {
var title: String
var ratings: [Int?]
}
有人知道如何解决这个问题吗?
这可以通过
解决
let sortedoptions = decisions[selectedDecision].options.sorted(by: { [=10=].ratings.reduce(0, {x,y in x + y!}) < .ratings.reduce(0, {x,y in x + y!})} )
这是因为错误提示无法对两种 Int?
类型执行加法。
此外,这是假设数组值永远不会为 nil
更安全的选择是将 y!
替换为 y ?? 0
我正在尝试对一个属性为可选的数组使用 .sorted,但出现此错误:
Ambiguous reference to member '+'
我不确定如何处理此处的可选项,并添加 !强制解包不起作用(我确定该数组在此代码运行时将具有值)。
let sortedoptions = decisions[selectedDecision].options.sorted(by: { [=11=].ratings.reduce(0, +) < .ratings.reduce(0, +) } )
和选项class:
struct Option: Codable {
var title: String
var ratings: [Int?]
}
有人知道如何解决这个问题吗?
这可以通过
解决let sortedoptions = decisions[selectedDecision].options.sorted(by: { [=10=].ratings.reduce(0, {x,y in x + y!}) < .ratings.reduce(0, {x,y in x + y!})} )
这是因为错误提示无法对两种 Int?
类型执行加法。
此外,这是假设数组值永远不会为 nil
更安全的选择是将 y!
替换为 y ?? 0