转载

Swift Type Casting 笔记

0.Type casting in Swift is implemented with the is and as operators.

类型转换:

  1. 检查是否是某一类型;
  2. 检查是否 conform 某一协议;
  3. 转换成某一类型(不会真的转换);

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")
    }
}
原文  http://c0ming.me/swift-note-type-casting/
正文到此结束
Loading...