soumyamahunt
(Soumya Ranjan Mahunt)
1
Let's say I have a struct with a property containing optional value:
struct SomeStruct {
var someVal: Int?
}
I can create a WritableKeyPath to someVal field and assign non-optional value via the keyPath without any error:
var obj = SomeStruct()
let keyPath = \SomeStruct.someVal
obj[keyPath: keyPath] = 5
But when I wrap this assigning logic inside a generic type or a protocol with associated type I am getting compiler error to force-unwrap or provide default value, i.e for following GenericStruct implementation:
struct GenericStruct<T> {
let keyPath: WritableKeyPath<SomeStruct, T?>
func assign(to obj: inout SomeStruct, data: T) {
obj[keyPath: keyPath] = data
}
}
I am getting the following error in assign method:
Value of optional type 'T?' must be unwrapped to a value of type 'T'
Coalesce using '??' to provide a default when the optional value contains 'nil'
Force-unwrap using '!' to abort execution if the optional value contains 'nil'
I am confused why this error is given by compiler, shouldn't a non-optional value be assigned to an optional value for same type?
It's only a bug in Playgrounds, yeah?
soumyamahunt
(Soumya Ranjan Mahunt)
3
Yes, just checked, working fine in Swift package, bug is only for playground.