使用泛型和原始类型进行类型检查?

时间:2019-05-24 23:34:45

标签: ios swift generics

我上课

class SomeViewController<T: SomeViewModel>: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { ... }

另一个班级:

class AnotherViewController: UIViewController {
    private weak var someVC: UIViewController?
    ...
    func someFunc() {
        if someVC is SomeViewController { ... } // attempt 1
        // or
        if let vc = someVC as? SomeViewController { ... } // attempt 1
        ...
    }
    ...
}

我需要查看someVC是否为SomeViewController,以便可以访问与通用类型无关的实例变量。但是,通过attempt 1attempt 2进行检查时,检查总是失败,并且我的内部代码也永远不会执行。我如何查看它是否是类型,而不是特定的通用类型,例如我不必输入SomeViewModel的类型吗?

编辑:为清晰起见添加了更多代码。

2 个答案:

答案 0 :(得分:2)

这不起作用,因为Swift想要知道泛型的类型。如果您只想访问某个属性而无需处理通用属性,则可以将其提取到协议中。

protocol SomethingThatHasFoo {
  var foo: String { get }
}

class SomeViewController<T>: UIViewController, SomethingThatHasFoo {
  let foo = "foo"
}

class AnotherViewController {
  private weak var someVC: UIViewController?

  func someFunc() {
    if let vc = someVC as? SomethingThatHasFoo {
      print(vc.foo)
    }
  }
}

答案 1 :(得分:1)

这是一个有效的示例:

class SomeViewModel{}

class A: SomeViewModel{}

class SomeViewController<T: SomeViewModel> : UIViewController{}

class AnotherViewController {

  private weak var someVC: UIViewController?

  init(vc: SomeViewController<A>) {
      someVC = vc
  }

  func someFunc() {
      if someVC is SomeViewController<A> {
          print("\(String(describing: someVC))")
      }
      if let vc = someVC as? SomeViewController<A> {
          print("\(vc)")
      }
}

然后您必须像这样初始化它:

    let someVC = SomeViewController<A>()
    let anotherVC = AnotherViewController.init(vc: someVC)
    anotherVC.someFunc()

希望能回答您的问题