0

C++mutableキーワードに相当するものはありますか? 変化しない関数を含むプロトコルを実装する構造体がありますが、実装は内部的に内部状態を変化させます。プロトコル定義を変更せずに、関数を作成することなく、この関数によってクラスのメンバー 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 に答える