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 String
s? 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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With