0

mutableC++关键字在 swift 中是否有等价物?我有一个实现包含非变异函数的协议的结构,但是内部实现确实会改变内部状态。有没有办法通过这个函数使类的成员 var 可变,而不改变协议定义,使函数mutating

例如

public protocol P {
    // f is semantically unmutating
    func f
}

public struct S : P {
    // f is semantically unmutating, but does change some internal state
    public func f {
        v += 1
    }
    private var v: Int // How to mark this as mutable for internal purposes?
    ...
}
4

1 回答 1

0

I don't think there is a way to do what you are trying to do other than change the semantics of the protocol to mutating f()

Your only option is to create a new mutating version of protocol P MutatingP and then have the structure extend MutatingP. This can have the mutating func f() function which you can implement in the structure

This is essentially same as the other answer though.

Here's another very crooked solution. But it kind of satisfies your requirements. You will need to work with two global variables. An Int variable V and struct S variable aStruct. The code is is pretty much self explanatory. The biggest problem in this approach is that you cant have two struct instances at the same time. But this can be handled by using array of struct instead of a single struct.

Bottom line it kind of keeps the unmutating semantic of the protocol but still lets you mutate the variable. A simpler way could be devised using the same approach.

import UIKit

protocol P {
    func f()
}

var aStruct:S!
var V = 100 {
    didSet {
        print("changed V to \(V)")
        if var s = aStruct {
            s.v = 200
        }
    }
}

struct S : P  {
    var v:Int = 100 {
        didSet {
            aStruct = self
        }
    }
    init() {
        aStruct = self
    }
    func f() {
        V = 200
    }
}

let s = S()
s.f()
print("s.v = \(s.v)...aStruct.v = \(aStruct.v)")
于 2016-03-07T13:57:50.493 回答