Is there any way to initialize a Swift type by setting its properties via Key Path?
struct SomeStruct {
var number: Int
init(to number: Int) {
self.number = number // ok
}
init(viaKeyPathTo number: Int) {
self[keyPath: \.number] = number // error
}
}
Attempting to initialize via key path fails with the errors:
'self' used before all stored properties are initialized
Return from initializer without initializing all stored properties
If the property uses let rather than var, it gives the error:
Cannot assign through subscript: key path is read-only
Setting properties via key path in init appears to not function. Why not? Are there any workarounds?
Has this issue been discussed or proposed in the open source Swift Evolution process?