2017-02-16 52 views
0

如何检查两个UIViewController子类对象是否具有相同的子类?我有两个UIViewControllers,我需要比较,看看他们是否是UIViewController的相同的子类

+0

你觉得'如果让VC1作为? TheSubclass,vc2?作为TheSubclass {...}',还是你在寻找一个通用的解决方案,你甚至不知道子类? –

+0

我在比较两个子类,所以type(of:vc1)== type(of:vc2)应该是正确的实现,但我最终采取了更优雅的方法,在我的代码中找到。不过,我相信我会在未来找到这方面的用处。我发现更经常的是,不必键入检查是实现代码的不好方法。它类似于理论上知道它是父vc的孩子vc。无论如何感谢大家的时间! – Sethmr

回答

1

在斯威夫特3,您可以用(:)的方法类型比较对象的类型:

class VC1: UIViewController { 

} 

class VC2: UIViewController { 

} 

let vc1 = VC1() 
let vc2 = VC2() 

let typeComparisonResult = type(of: vc1) == type(of: vc2) 
+0

谢谢,我看到了typeof(vc1),但我没有看到swift 3的版本。很难找到这个答案,然后我认为它会是,但是我解决了我需要以代码方式做的事情。谢谢! – Sethmr

0

Swift允许通过使用is关键字进行类比较。例如,如果您有class aclass b,它们都是UIViewController的子类。然后你可以使用is关键字来确认。

class a:UIViewController 
{ 

} 

class b:UIViewController 
{ 

} 

let instanceA:a = a() 
let instanceB:b = b() 

if a is UIViewController && b is UIViewController 
{ 
    print("Both are subclasses of UIViewController") 
} 
相关问题