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