- 当数组中存有同一父类的不同子类时,该数组内容会被统一认定为是父类
- is和as的区别:is用来判断,返回Bool;as用来转换,返回可选类型
- 使用is来判断是否是某一子类
for item in library { if item is Movie { movieCount += 1 } else if item is Song { songCount += 1 } }
- 在某一类可能实际上是其子类,并需要访问子类中属性时使用downcasting。由于转换可能会失败,使用as?表示可选,使用as!表示强制拆包
//Downcasting for item in library { if let movie = item as? Movie { print("Movie: \(movie.name), dir.\(movie.director)") } else if let song = item as? Song { print("Song: \(song.name), by \(song.artist)") } }
- swift中可以使用any代表所有类型实例,包括函数;可以使用anyobject代表所有类的实例
//Type Casting for Any and AnyObject 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.init(name: "Ghostbusters", director: "Ivan Reitman")) things.append({(name: String) -> String in "Hello, \(name)" }) for thing in things { switch thing { case 0 as Int: print("zero as an Int") case 0 as Double: print("zero as a Double") case let someInt as Int: print("an integer value of \(someInt)") case let someDouble as Double where someDouble > 0: print("a positive double value of \(someDouble)") case is Double: print("some other double value thar I don't want to print") case let someString as String: print("a string value of \"\(someString)\"") case let (x, y) as (Double, Double): print("an (x, y) point at \(x), \(y)") case let movie as Movie: print("a movie called \(movie.name), dir. \(movie.director)") case let stringConverter as (String) -> String: print(stringConverter("Michael")) default: print("something else") } }
- any可以代表任何类型包括可选,但是表示可选时加上as any来消除警告
let optionalNumber: Int? = 3 things.append(optionalNumber) // Warning things.append(optionalNumber as Any) // No warning
- Forced cast from 'Data?' to 'Data' only unwraps optionals; did you mean to use '!'?
当已知let originImage = UIImage(data: area.image as! Data)
area.image
为Data
类型时请不要使用as!
进行强制转换。只需要使用!
强拆即可。let originImage = UIImage(data: area.image!)
Type Casting
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 【Swift 3.1】19 - 类型转换 (Type Casting) 自从苹果2014年发布Swift,到现在已...