Xcode 8 beta 6: AnyObject替换为Any:其中是classForCoder



Xcode 8 beta 6将AnyObject替换为Any

在某些情况下,我使用a.classForCoder调试的原因,看看什么是在它。对于AnyObject,这是有效的。对于Any,这不再工作了。

现在我必须使用Any:查看Any类型变量中的类型的首选方法是什么?

转换到AnyObject似乎不是很有用,因为在许多情况下,这是一个StringString不再确认AnyObject自Xcode 8 beta 6。

Using type(of:)

您可以使用type(of:)来查找类型为Any的变量中的变量类型。

let a: Any = "hello"
print(type(of: a))  // String
let b: Any = 3.14
print(type(of: b))  // Double
import Foundation
let c: Any = "hello" as NSString
print(type(of: c))  // __NSCFString
let d: Any = ["one": 1, "two": "two"]
print(type(of: d))  //  Dictionary<String, Any>
struct Person { var name = "Bill" }
let e: Any = Person()
print(type(of: e))  // Person

使用classForCoder

classForCoder仍然存在,您可以将Any类型的值强制转换为AnyObject,但如果该值是Swift值类型,您将获得转换后的结果,而不是原始类型:

import Foundation // or import UIKit or import Cocoa
let f: Any = "bye"
print((f as AnyObject).classForCoder)  // NSString
print(type(of: f))                     // String
let g: Any = 2
print((g as AnyObject).classForCoder)  // NSNumber
print(type(of: g))                     // Int
let h: Any = [1: "one", 2: 2.0]
print((h as AnyObject).classForCoder)  // NSDictionary
print(type(of: h))                     // Dictionary<Int, Any>
struct Dog { var name = "Orion" }
let i: Any = Dog()
print((i as AnyObject).classForCoder)  // _SwiftValue
print(type(of: i))                     // Dog
// For an object, the result is the same
let j: Any = UIButton()
print((j as AnyObject).classForCoder)  // UIButton
print(type(of: j))                     // UIButton

相关内容

最新更新