I would like to create a set of objects that exhibit the following behavior:
- Each has a BOOL property — call it
dataLocked
— that is initially false. - Each has a set of stored properties whose values may be set, but not read, whenever
dataLocked == false
. - Those same stored properties may be read, but not set, whenever
dataLocked == true
dataLocked
can be set only once.
Below is a sample implementation. Is there any Swifty way to achieve this without having to reproduce all those get and set conditions for every property of every object?
The neatest solution I believe would be to create a Property Wrapper, but I haven’t found any way to make the wrapper change its behaviors based on the value of the `locked` property in the enclosing object.
class ImmutableObjectBase {
var dataLocked: Bool = false {
didSet { dataLocked = true }
}
private var _someIntValue: Int = 42
var someIntValue: Int {
get {
precondition(dataLocked, "Cannot access object properties until object is locked")
return _someIntValue
}
set {
precondition(!dataLocked, "Cannot modify object properties after object is locked")
_someIntValue = newValue
}
}
}
let i = ImmutableObjectBase()
i.someIntValue = 100
i.dataLocked = true // or false, it doesn't matter!
print (i.someIntValue) // 100
print (i.dataLocked) // true
i.someIntValue = 200 // aborts
2
Answers
Usage:
arsenius's answer here provided the vital reflection clue!
I found a solution for your problem, but it is probably not the cleanest way.
You might find a better way if you check this
or this.
I managed to lock and unlock the properties by using this tutorial:
EDIT:
I just found a similar question with an accepted answer.
Check here