Xcode 8 beta 6 已AnyObject
被Any
.
在某些情况下,我a.classForCoder
出于调试原因使用它来查看其中的内容。有了AnyObject
这个工作。有了Any
这个不再起作用。
现在我必须使用Any
:查看类型变量中的类型的首选方法是什么Any
?
Casting toAnyObject
似乎不是很有用,因为在许多情况下,这是一个String
并且自 Xcode 8 beta 6 以来String
不再确认。AnyObject
Xcode 8 beta 6 已AnyObject
被Any
.
在某些情况下,我a.classForCoder
出于调试原因使用它来查看其中的内容。有了AnyObject
这个工作。有了Any
这个不再起作用。
现在我必须使用Any
:查看类型变量中的类型的首选方法是什么Any
?
Casting toAnyObject
似乎不是很有用,因为在许多情况下,这是一个String
并且自 Xcode 8 beta 6 以来String
不再确认。AnyObject
You can use type(of:)
to find out what type of variable is in a variable of type 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
is still there, and you can cast a value of type Any
to AnyObject
, but if the value is a Swift value type, you'll get a converted result and not the original type:
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