我想要一个运行时测试来确定当前对象是否有超类。编译器拒绝
if super {
//do something
}
知道什么会起作用?
答案 0 :(得分:2)
我正在网上REPL测试这个,这就是我现在所拥有的一切。如果它在常规环境中不起作用,请告诉我,我会把它取下来......
你有几个选择。首先,您可以通过使用可选的as?
运算符进行强制转换来检查对象是否具有特定的超类:
class MyClass { }
class MySubClass: MyClass { }
let mSub: AnyObject = MySubClass()
if let m = mSub as? MyClass {
println("I am a subclass of MyClass")
}
如果您只是想知道对象是否有任何超类,并且您不知道超类可能是什么,您可以使用以下hack找出是否存在超类:
let mSub: AnyObject = MySubClass()
let description: String = {
var temp = String()
dump(mSub, &temp)
return temp
}()
if let r = description.rangeOfString("super") {
println("I am a subclass...")
}
应打印I am a subclass...
如果你想获得真正的hack-y,你可以像这样解析description
:
let charSet = NSCharacterSet(charactersInString: "\n ")
let classNames = description.componentsSeparatedByCharactersInSet(charSet).reduce([String]()) {
if let period = find($1, ".") {
let range = advance(period, 1)..<$1.endIndex
let className = $1.substringWithRange(range)
return $0 + [className]
}
return $0
}
如果您打印classNames
,则应获得:[MySubClass, MyClass]
// Edit: Update for Swift4, and wrapped into function
func classHierarchyTypeNames(for object: AnyObject) -> [String] {
let description: String = {
var temp = String()
dump(object, to: &temp)
return temp
}()
let charSet = CharacterSet(charactersIn: "\n ")
let classNames: [String] = description.components(separatedBy: charSet).reduce([String]()) {
// `description` includes quite a lot of non-class cruft.
// Check for an identifying prefix for your classes,
// as well as the `"."` character.
if ($1 as NSString).range(of: "<#MyFramework#>.").location != NSNotFound,
let period = $1.index(of: ".") {
let classNameStart = $1.index(period, offsetBy: 1)
let className = $1.suffix(from: classNameStart)
return $0 + [String(className)]
}
return $0
}
return classNames
}
答案 1 :(得分:1)
我建议使用返回可选AnyClass的superclass()方法,因此您基本上必须检查它是否返回nil。 (如果该类不继承自NSObject,则不会起作用)