[英]Swift: Implementing Comparable with computed struct property
I'm trying to implement comparable on a struct Pitch, that has a computed property called value. 我正在尝试在结构Pitch上实现可比性,该结构具有名为value的计算属性。 The computed property is marked 'mutating get' as it needs to modify this instance property. 计算出的属性被标记为“变异获取”,因为它需要修改此实例属性。 But when I try and extend so as to make the struct comparable, I get an error next to the return line saying: 但是,当我尝试扩展以使结构具有可比性时,在返回行旁出现错误:
Cannot use mutating getter on immutable value: 'lhs' is a 'let' constant 无法对不可变值使用变异吸气剂:“ lhs”是“ let”常量
extension Pitch: Comparable {
public static func < (lhs: Pitch, rhs: Pitch) -> Bool {
return lhs.value < rhs.value
}
Any idea how to fix this please? 知道如何解决这个问题吗?
Mainly Because Mutating is changing the value of a variable inside the Object. 主要是因为Mutating正在更改Object内部变量的值。
lhs & rhs // Are parameter.
And parameter are immutable (Constants) in Swift. 并且参数在Swift中是不可变的(常量)。
Therefore you can clone those Parameters into new Objects of Type var
and use their mutable Value
. 因此,您可以将这些参数克隆到var
类型的新对象中,并使用它们的可变Value
。
And because they're of type Struct
Value Type you can simply say this var newObj = myOldObj
. 而且因为它们的类型为Struct
Value Type,所以您可以简单地说这个var newObj = myOldObj
。
Your code could be something like this. 您的代码可能是这样的。
public static func < (lhs: Pitch, rhs: Pitch) -> Bool {
var lhsObj = lhs
var rhsObj = rhs
return lhsObj.value < rhsObj.value
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.