swiftimmutabilityglkit

In Swift, how do I add a setter to immutable GLKit vector structs?


In Swift GLKit vectors are immutable structs:

public struct _GLKVector2 {


    public var v: (Float, Float)

    public init(v: (Float, Float))

    public init()
}

extension GLKVector2 {

    public var x: Float { get }

    public var y: Float { get }

    public var s: Float { get }

    public var t: Float { get }

    public subscript(i: Int) -> Float { get }
}
public typealias GLKVector2 = _GLKVector2

I find this a bit restrictive and would like to extend GLKVector2 to include corresponding setters. How do I do this?


Solution

  • You could create a mutating func that replaces the whole self.

    extension GLKVector2 {
        mutating func setX(_ x: Float) {
            self = GLKVector2Make(x, y)
        }
    }
    
    ...
    
    v2.setX(123)
    

    You could create a property as well, but be careful you will need to write your own getter as well, and you can't return self.x there.

    var x: Float {
        get {
            return v.0
            // Note:
            //  1. you need to use a getter
            //  2. you cannot `return x`, otherwise it will be an infinite recursion
        }
        set {
            self = GLKVector2Make(newValue, y)
        }
    }