Why Xcode shows an error: Left side of mutating operator isn't mutable: result of conditional operator '? :' is never mutable?

Why Xcode shows an error: Left side of mutating operator isn't mutable: result of conditional operator '? :' is never mutable?

我正在重温 Apple Curriculum 书籍并尝试以不同的方式完成练习。问题很简单:我得到了一个数组,我必须遍历它来计算选票。

    enum ClassTripDestination {
        case beach, chocolateFactory
    }
    
    let tripDestinationVotes: [ClassTripDestination] = [.beach, .chocolateFactory, .beach, .beach, .chocolateFactory]

实际数组有200个值,我在这里缩短了它,这样它就不会占用太多space。


解决方法很简单:

var beach = Int()
var factory = Int()

for destination in tripDestinationVotes {
    if destination == .beach {
        beach += 1
    } else {factory += 1}
    
}

但我决定练习三元运算符并想出了这个:

for destination in tripDestinationVotes {
    destination == .beach ? beach += 1 : factory += 1

}

好吧,正如我的主题所述,Xcode 对这段代码不满意。

Left side of mutating operator isn't mutable: result of conditional operator '? :' is never mutable

但让我困扰的是,就在这个练习之前,我完成了另一个——非常相似。我不得不搜索一系列鸡肉。

var chickenOfInterestCount = 0
for chicken in chickens {
    chicken.temper == .hilarious ? chickenOfInterestCount += 1 : nil
}
chickenOfInterestCount

并且这段代码执行时没有出现任何问题。

谁能给我解释一下,为什么计算数组中的选票有问题?

好吧,事实证明解决方案非常简单。正如 Raja Kishan 所说,我只需要像这样在 beach += 1 周围放置大括号:

for destination in tripDestinationVotes {
    destination == .beach ? (beach += 1) : (factory += 1)

}

解决方法很简单,只需在 true 和 false 部分代码周围添加圆括号即可。

for destination in tripDestinationVotes {
    (destination == .beach) ? (beach += 1) : (factory += 1)
}

我认为您的代码 Xcode 只是因为有多个符号(例如等于或加号)而感到困惑。但是对于倒数第二个案例,很明显错误的部分是零并且正确地识别了真实的部分