Search code examples
swiftcomputed-properties

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?


Solution

  • 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
    }