Swift可选绑定,检查几种类型

时间:2017-12-06 09:42:53

标签: swift

我的班级模型可能是2个不同班级的实例。现在我检查该模型是否需要以下类:

 guard let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as myClassOne? else {
                assertionFailure("Wrong model for RetailSalesVC")
                return
            }

现在我想检查模型是否为第一类或模型是第二类。这有可能实现吗?

现在我最终得到了这个(但没有可选的绑定):

   guard (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassOne?) != nil)) ||
            (((store.state.navigationState.getRouteSpecificState(store.state.navigationState.route) as MyClassTwo?) != nil)) else {
                assertionFailure("Wrong model for \(self)")
                return
        }

3 个答案:

答案 0 :(得分:2)

如果你想运行它,这是一个例子:

class ModelOne {}
class ModelTwo {}

let testObjects : [Any] = [ModelOne.init(), ModelTwo.init(), NSCoder.init()]
for obj in  testObjects {
    if  (obj is ModelOne || obj is ModelTwo) {
        print("\(obj) passes")
    }else{
        print("\(obj) fails")
    }
}

应该给出以下输出:

main.ModelOne passes
main.ModelTwo passes 
<NSCoder: 0x7f93a0c02b40> fails

答案 1 :(得分:0)

    if unwrappedModel is ClassOne{
        print("this model is of type ClassOne")
    }
    else if unwrappedModel is ClassTwo{
        print("this model is of type ClassTwo")
    }

答案 2 :(得分:0)

试试这个

if let unwrappedModel = store.state.navigationState.getRouteSpecificState(store.state.navigationState.route){
    if unwrappedModel is MyClassOne{
        print("MyClassOne")
    }
    else if unwrappedModel is MyClassTwo{
        print("MyClassTwo")
    }
}