It seems empty arrays in Swift can be cast to any array type.
See the following example:
var obj = [Int]()
// compiler warns that this cast always fails, but this evaluates to true
print(obj is [String])
obj.append(3)
// This evaluates to false as expected
print(obj is [String])
This is easily verifiable in a playground, but will also happen in compiled code. Is this a known issue?
To declare an empty array for a type variable, set the array's type to Type[] , e.g. const arr: Animal[] = [] . Any elements you add to the array need to conform to the specific type, otherwise you would get an error.
arrays are objects, objects are truthy. just ask for array. length, if not zero, it will be truthy. when you explicitly convert to Boolean, the array turns into an empty string first, then the empty string turns into false.
Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”.
Technically you can't make an array empty. An array will have a fixed size that you can not change. If you want to reset the values in the array, either copy from another array with default values, or loop over the array and reset each value.
As @Hamish indicated, this is indeed a known issue. His comment points to bug report https://bugs.swift.org/browse/SR-6192 .
A workaround for this type logic seems to be
type(of: obj) == [SomeType].self
To expand on the example above,
var obj = [Int]()
obj is [String] // true
type(of: obj) == [String].self // false
type(of: obj) == [Int].self // true
obj.append(3)
obj is [String] // false
type(of: obj) == [String].self // false
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