How to get the base value from Swift KeyPath when its type is KeyPath <Root, Value!>?
Take a look at the following code:
struct Something {
var s: String! // Implicitly Unwrapped Optional
}
func bind<T, V>(keyPath: WritableKeyPath<T, V?>) {
}
bind(\Something.s)
The above code does not compile. If we replace the signature bind
with bind<T, V>(keyPath: WritableKeyPath<T, V>)
, then it compiles, but the problem is that the type V
is equal String!
, and I need to get the base type, in this case String
.
We can solve the problem as follows:
func bind<T, V>(keypath: WritableKeyPath<T, ImplicitlyUnwrappedOptional<V>>) {
}
Unfortunately, the documentation states that it is ImplicitlyUnwrappedOptional
out of date. However, it is not marked as deprecated with the attribute @available
.
I hesitate to use a type that docs says is deprecated, but I cannot find another way to accomplish what I need.
- Is there any other way to get an implicitly wrapped generic type
Value
fromWritableKeyPath
when its typeWritableKeyPath<T, V!>
? ImplicitlyUnwrappedOptional
- ?
Value
WritableKeyPath
,WritableKeyPath<T, V!>
?
, . , \Something.s
WritableKeyPath<T, V!>
. , SE-0054 (IUO , , ).
\Something.s
WritableKeyPath<T, V?>
, . .
ImplicitlyUnwrappedOptional
- ?
, SE-0054:
IUO , ,
ImplicitlyUnwrappedOptional
,ImplicitlyUnwrappedOptional<T>
. IUO . ,[Int!]
(Int!, Int!)
.
Swift 4, ImplicitlyUnwrappedOptional
, . Swift 5, , .
, IUO .