What about an empty array and generics in Swift?

Previously, we encountered an interesting mistake when working with generics in Swift. I understood the solution, but I am wondering if anyone can answer why the compiler will not catch something like this. Let me start with a block of code.

func doSomething<T>(with array: [T]) { type(of: array) // Optional<Array<Int>> array is [Int] // true 🙌 array is [String] // true 🤔 } var arrayOfInts: [Int] = [] doSomething(with: arrayOfInts) 

See line 4. Why the hell is this true ? Am I missing something? Should the compiler be smart enough to realize that it is not an array from String s? This ultimately led to an error when the value was set incorrectly due to an empty array, which was supposedly incorrect.

As for the solution, I went with something like:

 if type(of: array).Element.self == Model.self 
+5
source share
1 answer

In fact, this has nothing to do with the generic. Any empty array answers the question is with true if the type is an array:

 [Int]() is [String] // true [1] is [String] // false 

Seems strange; file with an error .

+6
source

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