检查“Any”值是否为object

时间:2016-08-27 19:25:46

标签: swift casting

我很惊讶地发现这种情况总是如此:

let foo: Any = 4
if let object = foo as? AnyObject {
    print("It's an object.")
    //do something with `object` that requires reference semantics
} else {
    print("It's not an object.")
}

似乎无论最初的foo类型是什么,它都会转换为相应类的实例。是否有可靠的方法来确定foo是否为对象?

2 个答案:

答案 0 :(得分:4)

更新

我在下面显示的代码报告为在发布版本中不起作用。 (请参阅Paul Cantrell的评论。)

为我和#34;道歉,就我测试而言#34;太有限了。

当我找到有关此内容的更多信息时,我会更新此答案。

我不确定我们是否可以在下一个测试版(或GM或已发布的版本...)中看到此行为,但这在Xcode 8 beta 6中的效果正常。

let foo: Any = 4
if type(of: foo) is AnyClass {
    print("It's an object.")
    let object = foo as AnyObject
    //do something with `object` that requires reference semantics
} else {
    print("It's not an object.") //->It's not an object.
}

class MyClass {}
let bar: Any = MyClass()
if type(of: bar) is AnyClass {
    print("It's an object.") //->It's an object.
    let object = foo as AnyObject
    //do something with `object` that requires reference semantics
} else {
    print("It's not an object.")
}

let baz: Any = Array<AnyObject>()
if type(of: baz) is AnyClass {
    print("It's an object.")
    let object = foo as AnyObject
    //do something with `object` that requires reference semantics
} else {
    print("It's not an object.") //->It's not an object.
}

我无法检查所有可能的情况,因此可能存在一些不起作用的边缘情况。但据我测试,这似乎按预期工作。

答案 1 :(得分:1)

也许你想看Mirror允许一定程度的内省。文档为here

import Foundation

func prettyPrint(_ any: Any) -> String {
    let m = Mirror(reflecting: any)
    switch m.displayStyle {
    case .some(.class): // ****
        return "Class"
    case .some(.collection):
        return "Collection, \(m.children.count) elements"
    case .some(.tuple):
        return "Tuple, \(m.children.count) elements"
    case .some(.dictionary):
        return "Dictionary, \(m.children.count) elements"
    case .some(.set):
        return "Set, \(m.children.count) elements"
    case .some(.optional):
        return "Optional"
    case .some(.enum):
        return "Enum"
    case .some(.struct):
        return "Struct"
    default:
        return "\(String(describing: m.displayStyle))"
    }
}
class A {}

prettyPrint([1, 2, 3]) // "Collection, 3 elements"
prettyPrint(Set<String>()) // "Set, 0 elements"
prettyPrint([1: 2, 3: 4]) // "Dictionary, 2 elements"
prettyPrint((1, 2, 3)) // "Tuple, 3 elements"
prettyPrint(3) // "nil"
prettyPrint("3") // "nil"
prettyPrint(NSObject()) // "Class"
prettyPrint(NSArray(array:[1, 2, 3])) // "Collection, 3 elements"
prettyPrint(A()) // "Class"

// prettyPrint(nil) // Compile time error "Nil is not compatible with Any