在 Swift 中,如何将 setter 添加到不可变的 GLKit 向量结构?

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

在 Swift GLKit 中向量是不可变结构:

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

我觉得这有点限制,想扩展 GLKVector2 以包含相应的设置器。我该怎么做?

您可以创建一个替换整个 self 的变异函数。

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

...

v2.setX(123)

您也可以创建一个 属性,但请注意,您还需要编写自己的 getter,而您不能在那里 return self.x

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