Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty array can be cast to array of any type

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?

like image 886
kid_x Avatar asked Feb 12 '18 18:02

kid_x


People also ask

What is the type of an empty array?

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.

Is empty array True or false?

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.

Can you create an empty array?

Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”.

Can you have empty arrays in C?

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.


1 Answers

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
like image 69
kid_x Avatar answered Sep 24 '22 06:09

kid_x