【问题标题】:Xcode 8 beta 6: AnyObject replaced by Any: where is classForCoder?Xcode 8 beta 6:AnyObject 替换为 Any:classForCoder 在哪里?
【发布时间】:2016-08-15 21:30:10
【问题描述】:

Xcode 8 beta 6 已将 AnyObject 替换为 Any

在某些情况下,出于调试原因,我使用a.classForCoder 来查看其中的内容。使用AnyObject 这有效。对于Any,这将不再起作用。

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

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

【问题讨论】:

    标签: swift swift3 xcode8-beta6


    【解决方案1】:

    使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多