An empty array declared by Swift is treated as NSArray unless I give a type annotation
While I am playing with Swift Array I am facing a problem.
Below is my experiment:
var iArray = [] //Here if I see the type details in quick help it is of NSArray type.
var myArray = [Int]() //Here if I see the type details in quick help it is of Swift Array<Int> type.
Now if I check like below
if iArray is NSArray { //it gives error saying it is always true, which is correct.
println("Confused")
}
if iArray is Array<String> { //Here it is true and printing the message and same is also true if i check for Array<Int>
println("More Confused")
}
According to the Swift documentation, Array is equivalent NSArray
. Should I understand that the quick help is giving the wrong information? More explanation would be great at this stage.
source to share
var iArray = []
creates empty NSArray
. (This array is pretty useless because it NSArray
is immutable, so you cannot add any elements to it.)
if iArray is Array<String> { ... }
checks if each element is in the array (or can be bound to) a String
. The array has no elements, so the check ends - "empty truth" . If you change the code to var iArray : NSArray = [ 1 ]
, then this check will fail.
The force press will be successful:
for s in iArray as! Array<String> {
println(s.lowercaseString)
}
and this is not a problem, because the body of the loop is never executed.
source to share