Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's with empty arrays and generics in Swift?

Tags:

generics

swift

Ran across an interesting bug earlier today when working with generics in Swift. I figured out a solution, but I'm wondering if anyone can answer why the compiler does 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 heck is that true? Am I missing something? Shouldn't the compiler be smart enough to figure out this isn't an array of Strings? This ultimately led to a bug where a value was set incorrectly due to the empty array assumed to be of the wrong type.

As far as a solution, I went with something along the lines of:

if type(of: array).Element.self == Model.self
like image 555
SeeMeCode Avatar asked Dec 24 '17 03:12

SeeMeCode


People also ask

Should I use null or empty array?

NET it's better to return an empty array than null because it saves the caller having to write a null check and/or risking a NullReferenceException ; you'll see this is a common pattern in the base class libraries.

What is generic in Swift?

Generics in Swift allows you to write generic and reusable code, avoiding duplication. A generic type or function creates constraints for the current scope, requiring input values to conform to these requirements.

How do I check if an array is empty in Swift?

In the Swift array, we check if the given array is empty or not using the isEmpty property. This property is used to find whether the given array is empty or not. If the given array is empty then this property will return true otherwise it will return false.


1 Answers

Actually it has nothing to do with the generic. Any empty array answers the is question with true if the type is an array:

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

It does seem odd; file a bug.

like image 174
matt Avatar answered Oct 04 '22 17:10

matt