【发布时间】:2015-08-06 07:22:48
【问题描述】:
我很快就被这个问题困住了。假设我有一个对象,如何快速检查它是来自结构体还是类。
【问题讨论】:
-
看起来在 Swift 3 中是不可能的。但是类对象有 superclass 属性而结构对象没有。
我很快就被这个问题困住了。假设我有一个对象,如何快速检查它是来自结构体还是类。
【问题讨论】:
在 Swift 3.0 中,您可以调用 Mirror(reflecting:x).displayStyle,其中 x 是您感兴趣的值。结果将是class、struct、enum、dictionary、set...参见文档https://developer.apple.com/reference/swift/mirror.displaystyle
代码示例:
struct SomeStruct {
var name: String
init(name: String) {
self.name = name
}
}
var astruct = SomeStruct(name:"myname")
Mirror(reflecting:astruct).displayStyle == .struct // will be true
Mirror(reflecting:astruct).displayStyle == .class; // will be false
class MyClass {
var name:String
init(name: String) {
self.name=name
}
}
var aclass = MyClass(name:"fsdfd")
Mirror(reflecting:aclass).displayStyle == .struct // will be false
Mirror(reflecting:aclass).displayStyle == .class // will be true
当然,在实践中最好使用 switch-case 语句来处理。
【讨论】:
这种方法在 Swift 3 中一直对我有用:
class TestClass { }
struct TestStruct { }
var mystery:Any
mystery = TestClass()
// Is mystery instance a class type?
print(type(of:mystery) is AnyClass ? "YES" : "NO") // prints: "YES"
mystery = TestStruct()
// Is mystery instance a class type?
print(type(of:mystery) is AnyClass ? "YES" : "NO") // prints: "NO"
请注意,这种方法仅告诉您实例是否为类类型。它不是一个类的事实并不一定意味着它是一个结构(可能是一个枚举、闭包、元组等)但是对于大多数目的和上下文来说,这足以知道你是否正在处理使用引用类型或值类型,这通常是需要的。
【讨论】:
有is 运算符。
if someInstance is SomeType {
// do something
}
还有as?运算符。
if let someInstance = someInstance as? SomeType {
// now someInstance is SomeType
}
【讨论】:
在swift4中,检查类或结构
class TClass {}
struct TStruct {}
func who(_ any: Any) -> String {
if Mirror(reflecting: any).displayStyle == .class {
return "Class"
} else {
return "Struct"
}
}
print(who("Hello")) // Struct
print(who(TClass())) // Class
print(who(TStruct())) // Struct
print(who(1)) // Struct
【讨论】:
你可以通过下面给定的方式和for more information on this please follow this link来做到这一点。
class Shape {
class func className() -> String {
return "Shape"
}
}
class Square: Shape {
override class func className() -> String {
return "Square"
}
}
class Circle: Shape {
override class func className() -> String {
return "Circle"
}
}
func getShape() -> Shape {
return Square() // hardcoded for example
}
let newShape: Shape = getShape()
newShape is Square // true
newShape is Circle // false
newShape.dynamicType.className() // "Square"
newShape.dynamicType.className() == Square.className()
【讨论】:
一个简单的例子:
var name = "Big Hero"
if name.isKindOfClass(NSString){
println("this is this class")
}else{
println("this is not this class")
}
【讨论】: