Swift入门教程13-类型转换is as any anyobject

来源:互联网 发布:unity3d汉化版下载 编辑:程序博客网 时间:2024/05/17 21:27
原创Blog,转载请注明出处
如果有不懂的地方
参照我的swift入门教程
http://blog.csdn.net/column/details/swift-hwc.html
类型转换的关键字
is 判断是否是某种类型
as 强制转换为某种类型
as? 可选转换为某种类型,转换结果为可选类型,转换失败为nil
Any 任意类型的常量、变量(不包括函数类型)
Anyobject 任意class类型的实例

首先定义一个基类和两个子类
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类型

一、is 用来检查类型
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 Subclass1caseResult.sub1Print()}
上面这段代码会报出运行期错误,因为数组的第二个强制转型会失败
注意:使用as 一定要保证转换会成功,不确定请使用下面的as?


三、用as?来类型转换
for temp in array{if let caseResult = temp as? Subclass1{caseResult.sub1Print()}}
这段代码不会失败


四、AnyObject 和 Any 
当然这两个也有可选类型Any?和AnyObject?
和普通的可选类型使用方式大致一样,这里不多做讲解,侧重讲解本身内容
AnyObject和Objective C中的ID类型十分相似
所以,在Cocoa中,很多方法都会以AnyObject为参数,返回值也有很多AnyObject和Any类型

前面讲解过,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类型的数组

然后,我们再用上面讲到的as 和 as?转换为我们使用的类型
AnyObject例子
在开发的过程中,经常我们用到Fundation中的NSArray,NSSet,NSDictionary等类型
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 Stringprintln(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进行强制转换,但是不会产生类型错误,匹配并且转换成功,才会执行相应的语句
比如这一句 case let (x, y) as (Double, Double):先会匹配是否是元组,并且有两个元素,然后再进行转换,转换成功了再打印
3 0