Xcode 8 beta 6已经取代Any的AnyObject.
在某些情况下,我使用a.classForCoder进行调试,以查看其中的内容.使用AnyObject,这很有效.随着任何这不再起作用.
现在我必须使用Any:在Any类型的变量中查看哪种类型的首选方法是什么?
转换为AnyObject似乎不是很有用,因为在许多情况下这是一个字符串,并且自Xcode 8 beta 6以来字符串不再向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
使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。