简体   繁体   中英

Swift: Implementing Comparable with computed struct property

I'm trying to implement comparable on a struct Pitch, that has a computed property called 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

  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.

lhs & rhs  // Are parameter.

And parameter are immutable (Constants) in Swift.

Therefore you can clone those Parameters into new Objects of Type var and use their mutable Value .

And because they're of type Struct Value Type you can simply say this 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM