【问题标题】:Cannot use mutating member on immutable value Swift不能在不可变值 Swift 上使用变异成员
【发布时间】:2019-07-09 08:00:20
【问题描述】:

我想为Double 写一个扩展,这样它就可以给Int 值。

extension Double {
  func toPercentage() -> Int {
    var mutableSelf = self
    var twoDigits = Double(round(1000*mutableSelf)/1000)
    return Int(twoDigits) * 100
  }
}

在线var twoDigits = Double(round(1000*mutableSelf)/1000)编译器抛出红色-Cannot use mutating member on immutable value: 'self' is immutable

但我确实将 self 重新分配给了 mutableSelf 变量。 Double是struct,不是引用类型,为什么会报错?

【问题讨论】:

  • 试试var mutableSelf = Double(self)?
  • @zaitsman 是对 Double 的扩展,对 Double(self) 有什么意义?

标签: swift


【解决方案1】:

由于您位于Double 的扩展中,因此编译器将round() 推断为Doublemutating func round() 方法,即使该调用与其签名不匹配。此行为已被报告为错误:

可以参考全局C库函数

extension Double {
    func toPercentage() -> Int {
        let twoDigits = Darwin.round(1000*self)/1000
        return Int(twoDigits * 100)
    }
}

或者更好,使用Double.rounded() 方法:

extension Double {
    func toPercentage() -> Int {
        let twoDigits = (1000*self).rounded()/1000
        return Int(twoDigits * 100)
    }
}

或者干脆

extension Double {
    func toPercentage() -> Int {
        return Int((100 * self).rounded())
    }
}

【讨论】:

    【解决方案2】:
    extension Double {
        func toPercentage() -> Int {
            let twoDigits = Double((1000 * self / 1000).rounded())
            return Int(twoDigits) * 100
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2021-10-12
      • 1970-01-01
      • 2019-03-23
      • 2020-08-08
      • 2020-01-28
      相关资源
      最近更新 更多