Ger*_*tan 5 swift swift3 xcode8-beta6
xcode的8个β6取代AnyObject通过Any.
在某些情况下,我用于a.classForCoder调试原因,看看它里面有什么.有了AnyObject这个工作.有了Any这不起作用了.
现在我必须使用Any:在类型变量中查看哪种类型的首选方法是什么Any?
转换AnyObject似乎不是非常有用,因为在许多情况下这是一个String并且自Xcode 8 beta 6以后String不再确认AnyObject.
您可以使用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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1711 次 |
| 最近记录: |