将 Objective-C id
类型的实例转换为特定的 Swift 类型。
概览
在 Objective-C 中,id
类型表示属于任何 Objective-C 类的实例的对象。不过,Swift 将 id
类型作为 Any
类型导入。将 Swift 实例传递给 Objective-C API 时,它会作为 id
参数来桥接,以便能够在 API 中作为 Objective-C 对象来使用。当 id
值作为 Any
导入到 Swift 中时,运行时会自动处理回到类引用或值类型的桥接。
var x: Any = "hello" as String
x as? String // String with value "hello"
x as? NSString // NSString with value "hello"
x = "goodbye" as NSString
x as? String // String with value "goodbye"
x as? NSString // NSString with value "goodbye"
向下转换对象来调用方法和访问属性
在处理 Any
类型的对象时,如果你知道其基础类型,将这些对象向下转换为基础类型通常很有用。不过,由于 Any
类型可以引用任何类型,编译器无法保证能够成功地向下转换为更具体的类型。
你可以使用条件判断类型转换运算符 (as?
),这会返回你想要尝试向下转换到的类型的一个可选值:
let userDefaults = UserDefaults.standard
let lastRefreshDate = userDefaults.object(forKey: "LastRefreshDate") // lastRefreshDate is of type Any?
if let date = lastRefreshDate as? Date {
print("\(date.timeIntervalSinceReferenceDate)")
}
如果你十分确定对象的类型,可以改为使用强制向下转换运算符 (as!
)。
let myDate = lastRefreshDate as! Date
let timeInterval = myDate.timeIntervalSinceReferenceDate
不过,如果强制向下转换失败,会触发运行时错误:
let myDate = lastRefreshDate as! String // Error