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 bindwith bind<T, V>(keyPath: WritableKeyPath<T, V>), then it compiles, but the problem is that the type Vis 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 ImplicitlyUnwrappedOptionalout 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 Valuefrom WritableKeyPathwhen its type WritableKeyPath<T, V!>?
  • ImplicitlyUnwrappedOptional - ?
+4
1

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 ​​ .

+3

Source: https://habr.com/ru/post/1688566/


All Articles