如何在Swift中将UIViewController转换或类型转换为AnyClass

时间:2016-06-22 11:39:39

标签: ios swift casting ios8

我只想将任何UIViewController子类转换为AnyClass以便从isKindOfClass方法进行检查,因为此方法将AnyClass作为参数。

3 个答案:

答案 0 :(得分:3)

您可以在swift中使用Objective-Cas关键字,而不是使用旧的is API。

if let controller = yourViewController as? SomeClass {
    // use controller, is already casted to SomeClass
}

if yourViewController is SomeClass {
    let controller = yourViewController as! SomeClass
    // use controller now
}

<强>添加: 如果内存地址不同,则对象不相等。尝试检查我在答案中提到的topViewController类型。

if let topViewController = appDelegateObj.navigationController.topViewController as? YOUR_VIEW_CONTROLLER_CLASS {
     // do something 
}

答案 1 :(得分:1)

func someMethod (someClass : AnyClass) {
   if someClass is YourClass {
     someClass.someMethodOfYourClass()
   }
}

使用此方法

class YouClass: UIViewController {

   func something() {
    someMethod(self)    // sending itself (a.k.a) YourClass

   }
}

希望这有帮助

根据评论进行编辑:

let controller = appDelegateObj.navigationController!.topViewController

if controller is ClassName {
    // controller good  to use
 }

答案 2 :(得分:0)

最后我达成了这个解决方案

let name = NSStringFromClass((vcAnyObj?.classForCoder)!) 
let name2 = NSStringFromClass((appDelegateObj.navigationController!.topViewController?.classForCoder)!) 

if name == name2 { 
print("same view controller") 
}else { 
print("different view controller") 

}