2017-04-17 42 views
2

我见过各种各样的回答在这里类似的问题,但这是不同的(特别是,这个非常广泛的答案here没有帮助Swift 3:如何*指定*对象的类,排除父成员?

让我解释一下:如果你是一个父类的范围内,如何能你 - 在短短的一行代码 - 排除的对象恰恰是这个类的一个实例,但不是所有的类孩子的班级

代码示例的一个实例:

class Subchild: Child { 
    //blabla 
} 

class Child: Parent { 
    //blabla 
} 

class Parent { 
    //....could be NSObject or generic Swift class 
    func iAmNotARealParent() -> Bool { 
     enter code here 
    }  
} 

.. 。我可以这样做:

let myObject:Subchild = ... 
myObject.iAmNotARealParent() //<--- returns true 

let anotherObject:Child = ... 
anotherObject.iAmNotARealParent() //<---- returns true 

let thirdObject:Parent = ... 
thirdObject.iAmNotARealParent() //<---- returns false 

在我的特殊情况下,我正在处理尝试在UIViews内部识别“self”是实际的UIView还是它的任何多个子类(UIButton等)。 我做希望有检查它是这样的:

if self is UIBUtton {return false} 
if self is UIScrollView {return false} 

等,因为那时我已经明确排除所有子类。

我该怎么做? Swift中是否存在* exactClassOf/exactTypeOf *函数?注意:我要找两个斯威夫特衍生和NSObject的派生类的解决方案(即用于任何

回答

1

您可以使用类似:

if type(of: self) == Parent.self { 
    // this only runs for exact type matches, not subclasses 
} 

,检查为类型的平等,而比实例的多态一致性(即self is Parent

+0

啊 - 优雅!谢谢! – Averett