0.Type casting in Swift is implemented with the is and as operators.
类型转换:
1. as、as?、as!
as 用于 upcasting 和 type casting to bridged type
as? and as! 用于 downcasting
class Media { var name :String = "" init(name:String) { self.name = name } } class Song:Media {} let s1 = Song(name :"Fireproof") let m1 = s1 as Media // upcasting // let m1: Media = s1 let s2 = m1 as? Song // downcasting // let s2 = m1 as! Song let s = "jj" as NSString // type casting to bridged type
2.Casting does not actually modify the instance or change its values.
3.Type Casting for Any and AnyObject
let dict = ["someKey": 2] as [String: Any] // let dict: [String: Any] = ["someKey": 2] for (key, value) in dict { if let d = value as? Double { print(d) } else if let i = value as? Int { print(i) } switch value { case let d as Double: // cast bind to a constant print(d) case let i as Int: print(i) default: print("not match") } }