declared Swift empty Array is treated as NSArray if i am not giving type annotation

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

While I am playing with Swift Array I came across a problem.
Here 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") } 

As per documentation, Swift Arrays are equivalent to NSArray. Should I understand that quick help is giving wrong information? More explanation would be great at this point.

回答1:

var iArray = [] 

creates an empty NSArray. (This array is pretty useless because NSArray is immutable, so you cannot add any elements to it.)

if iArray is Array<String> { ... } 

checks if each element in the array is (or can be bridged to) a String"vacuous truth". If you change your code to var iArray : NSArray = [ 1 ] then this check would fail.

A forced cast would succeed as well:

for s in iArray as! Array<String> {     println(s.lowercaseString) } 

and that is no problem because the loop body is never executed.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!