Swift type selection not applicable

If I understand correctly, Swift can determine the actual type of generics in various ways, including matching by return type. The same (or similar) mechanism is used to eliminate ambiguous overloaded functions. Thus, this works as expected:

func getValue<T>()->T? { return nil } func getValue()->Int? { return 13 } let b: Int? = getValue() 

When doing this, b will be 13 . Technically, both function signatures are suitable, but the latter is more specific to the requested return type.

Add a second function and pass it through the tunnel:

 func getGetValue<T>()->T? { return getValue() } let c: Int? = getGetValue() 

When doing this, c will be nil . In fact, the compiler will choose the general implementation of getValue (), which will be called from getGetValue (), which I don't want. IMHO, the requested return value type must propagate over the second common one when choosing between two implementations of getValue (), which leads to the same behavior as in the first example.

What am I missing? (Xcode 7.1)

+5
source share
1 answer

I tried to explicitly propagate the generic type, and it still doesn't work (which means you're right, this is the problem):

 func getGetValue<T>()->T? { guard let value: T? = getGetValue() return value } 

Here is a slightly different approach that can get what you are looking for using the protocol (using the protocol allows us to store some type information)

 // Protocol for getting a value protocol GetValue { static func getValue() -> Self? } // Default implementation extension GetValue { static func getValue() -> Self? { return nil } } // Int implementation extension Int: GetValue { static func getValue() -> Int? { return 13 } } // Our generic getGetValue function for any type that implements GetValue func getGetValue<T: GetValue>()->T? { return T.getValue() } let a: Int? = getGetValue() // 13 // Making String implement the protocol (It gets the default implementation) extension String: GetValue { } let b: String? = getGetValue() // nil 
0
source

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


All Articles