【问题标题】:Why Xcode shows an error: Left side of mutating operator isn't mutable: result of conditional operator '? :' is never mutable?为什么 Xcode 显示错误:变异运算符的左侧不可变:条件运算符的结果'? :' 永远不可变?
【发布时间】:2021-08-22 18:43:07
【问题描述】:

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

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

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


解决方法很简单:

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 对此代码并不满意。

变异运算符的左侧不可变:条件的结果 操作员 '? :' 永远不可变

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

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

并且这段代码的执行没有任何问题。

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

【问题讨论】:

  • 尝试为大小写 true 和 false 添加圆括号。喜欢(海滩 += 1)
  • 试试beach += destination == .beach ? 1 : 1
  • @Raja Kishan 有时我不明白 Xcode 下一步会做什么。这确实解决了这个问题。
  • @Tushar Sharma 为了让它工作,冒号后面应该是“0”。而且只会增加海滩变量。
  • 虽然其他人已经回答了您的特定语法问题,但我建议您考虑使用 Dictionary<ClassTripDestination, Int> 来模拟投票计数。它更短更简单,请参阅:stackoverflow.com/a/41841238/3141234

标签: arrays swift for-loop conditional-operator


【解决方案1】:

解决方案很简单,只需在真假部分代码周围添加圆括号即可。

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

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

【讨论】:

  • 我也会在destination == .beach 周围加上括号。它们不是必需的,因为 == 的优先级高于 ? :,但它们会使其更易于阅读。
【解决方案2】:

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

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

}

【讨论】:

  • 让 raja 发布这个,这样你就可以奖励他了。
  • @Tushar Sharma 如果他发布它,我会将其设置为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
  • 2021-12-02
  • 2021-01-06
  • 2022-10-15
  • 2017-07-16
  • 2016-08-20
相关资源
最近更新 更多