class Base{ var baseVar:String = "base" } class Subclass1:Base{ var subVar1:String = "subvar1" func sub1Print(){ println(subVar1) } } class Subclass2:Base{ var subVar2:String = "subvar1" func sub2Print(){ println(subVar2) } } var array:[Base] = [Subclass1(),Subclass2()]//数组的类型是Base类型
for temp in array{ if temp is Subclass1{ println("sub1") } if temp is Subclass2{ println("sub2") } }二、用 as 来类型转换
for temp in array{ var caseResult= temp as Subclass1 caseResult.sub1Print() }上面这段代码会报出运行期错误,因为数组的第二个强制转型会失败
for temp in array{ if let caseResult = temp as? Subclass1{ caseResult.sub1Print() } }这段代码不会失败
前面讲解过,swift的数据结构,Array和Dictionary的数据类型必须确定,但是有了Any和AnyObject之后,我们可以更加灵活的使用,例如
var funnyDictionary = Dictionary<String,AnyObject>()//定义key为String,Value是AnyObject类型 var complexDictionary = Dictionary<String,Dictionary<Int,[Any]>>//定义key是String,Value是字典类型,这个字典的key是Int,value是Any类型的数组 var funnyArray = [Any]()//定义Any类型的数组
var hwcArray = [AnyObject]() var hwcNSArray = NSArray(objects:"123","456",NSNumber(double:4.0)) var hwcNSDictionary = NSDictionary(object:"value",forKey:"key") hwcArray.append(hwcNSArray) hwcArray.append(hwcNSDictionary) for temp in hwcArray{ if let result = temp as? NSArray{ println(temp.count) } if let result = temp as? NSDictionary{ var value = temp.valueForKey("key") as String println(value) } }
这里要说明的是valueForKey会返回AnyObject?,所以要转换为我们需要的String类型
官方文档Any例子:var things = Any[]() things.append(0) things.append(0.0) things.append(42) things.append(3.14159) things.append("hello") things.append((3.0, 5.0)) things.append(Movie(name: "Ghostbusters", director: "Ivan Reitman")) for thing in things { switch thing { case 0 as Int: println("zero as an Int") case 0 as Double: println("zero as a Double") case let someInt as Int: println("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0: println("a positive double value of \(someDouble)") case is Double: println("some other double value that I don't want to print") case let someString as String: println("a string value of \"\(someString)\"") case let (x, y) as (Double, Double): println("an (x, y) point at \(x), \(y)") case let movie as Movie: println("a movie called '\(movie.name)', dir. \(movie.director)") default: println("something else") } } // zero as an Int // zero as a Double // an integer value of 42 // a positive double value of 3.14159 // a string value of "hello" // an (x, y) point at 3.0, 5.0 // a movie called 'Ghostbusters', dir. Ivan Reitman在switch中,可以用as进行强制转换,但是不会产生类型错误,匹配并且转换成功,才会执行相应的语句