I understand how to create an AnyThing
type erasure like below, when I have just getters. But when I try to add the setter for field
on the AnyThing
I get a compiler error. I'm not sure how to proceed. Any recommendations?
The error: Cannot assign to property: 't' is a 'let' constant
protocol Thing {
var field: String { get set }
// ... imagine other req's that make it unusable except as a generic constraint
}
class Thing1: Thing {
var field: String = "hi"
}
/// A type-erased Thing
struct AnyThing {
let thing: Any
let getField: () -> String
let setField: (String) -> Void
init<T: Thing>(_ t: T) {
self.thing = t
self.getField = { t.field }
self.setField = { t.field = $0 } // <-- error here
}
var field: String {
get { getField() }
set { setField(newValue) }
}
}
let thing = Thing1()
let anyThing = AnyThing(thing)
print("thing.field = \(thing.field)")
print("anyThing.field = \(anyThing.field)")
anyThing.field = "hola"
print("anyThing.field = \(anyThing.field)")