gpt4 book ai didi

swift - 确定 swift 对象是否具有父类(super class)

转载 作者:行者123 更新时间:2023-11-28 11:20:27 25 4
gpt4 key购买 nike

我想要一个运行时测试来确定当前对象是否有父类(super class)。编译器拒绝

if super {
//do something
}

知道什么会起作用吗?

最佳答案

我正在在线 REPL 上对此进行测试,因为我目前只有这些。如果它在常规环境中不起作用,请告诉我,我会把它记下来...

您有几个选择。首先,您可以通过使用可选的 as? 运算符进行强制转换来检查对象是否具有特定的父类(super class),如下所示:

class MyClass { }
class MySubClass: MyClass { }

let mSub: AnyObject = MySubClass()

if let m = mSub as? MyClass {
println("I am a subclass of MyClass")
}

如果您只想知道该对象是否有任何父类(super class),而您不知道该父类(super class)可能是什么,您可以使用以下 hack 找出是否有父类(super class):

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
}

关于swift - 确定 swift 对象是否具有父类(super class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28629943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com