【问题标题】:Better way to check the instance is kind from list of classes?检查实例的更好方法是类列表中的种类?
【发布时间】:2018-05-01 10:05:09
【问题描述】:

目前在 swift 中,我们可以使用 'is' 运算符来检查实例的类类型。 例如:

....
guard anyInstance is MYClass else {
    return
}
....

就我而言,我需要将同一个实例与多个类类型进行比较, 例如:

...
    if anyInstance is MyClassOne ||
          anyInstance is MyClassTwo || anyInstance is MyClassThree {
          return
        }
...

有没有更好的方法来快速编写这种条件?像

....

if anyInstance is (MyClassOne, MyClassTwo, MyClassThree) {
return
}
...

【问题讨论】:

  • 你为什么要检查它?知道一个对象是否是三个可能类之一的实例有什么帮助?为了调用对象上的任何特定方法,无论如何您都必须(有条件地)强制转换它。 – 也许您想定义一个公共超类或这些类所遵循的协议?
  • 你可以在 switch 语句中使用case is MyClass,但是@MartinR 建议使用一个通用的超类是好的。
  • 嗨,马丁,感谢您的回复。就我而言,“anyInstance”属于 UIViewController 类型,如果“anyInstance”属于 MyClass* 类型,我不想调用 dismiss() 方法。
  • 如果anyInstance 应该是UIViewController 为什么不检查... is UIViewController 而不是is not A || is not B || is not C ??

标签: ios swift swift3


【解决方案1】:

如果我从逻辑上考虑,为它们定义一个超类/协议会更有意义,如下所示:

class MyClassNumber { }

class MyClassOne: MyClassNumber { }
class MyClassTwo: MyClassNumber { }
class MyClassLetter { }

let one = MyClassOne()
let two = MyClassTwo()
let letter = MyClassLetter()

if one is MyClassNumber {
    // TRUE
}

if two is MyClassNumber {
    // TRUE
}

if letter is MyClassLetter {
    // FALSE
}

没有看到任何适合您的用例

【讨论】:

    【解决方案2】:

    根据您的评论,您似乎需要它来检查您的anyInstance 是否来自UIViewController 的列表,然后您不想致电dismiss()

    没有任何方法,您可以将数组传递为:

    if anyInstance is (MyClassOne, MyClassTwo, MyClassThree) {
        return
    }
    

    但是,您可以使用 switch 语句来执行此操作:

    假设anyInstance 是你的类对象

        switch anyInstance {
        case is MyClassOne, is MyClassTwo ,is MyClassThree:
            print("one is either from MyClassOne, MyClassTwo, MyClassThree")
        default:
            break
        }
    

    【讨论】:

      【解决方案3】:
      class MyClassOne: MyClassNumber { }
      class MyClassTwo: MyClassNumber { }
      class MyClassThree: MyClassNumber { }
      
      Inherit all class from one class and than check after that like
      
          if anyInstance is BaseClass{
          }
      

      【讨论】:

      • 感谢您的回答!但是请花几分钟时间阅读how to answer 以获得一些有用的回答问题的技巧。特别是。 “解释得越详细越好”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 2019-10-23
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多