无法转换类型' P?'的返回表达式返回类型' UIViewController'

时间:2017-12-13 09:52:11

标签: ios swift

我的协议只适用于UIViewController类

我有一组必须响应P协议的对象

所以当从数组返回一个对象时,我确信得到一个UIViewController类对象。

为什么编译器会返回错误:

  

无法转换类型' P'的返回表达式返回类型   '的UIViewController'?

protocol P where Self: UIViewController {
    func f ()
}

class A: UIViewController {

    let d: [P] = [P]()

    func m() -> UIViewController? {

        return self.d.first

    }

}

3 个答案:

答案 0 :(得分:1)

目前,编译器并不知道[P]只包含UIViewController个实例。它可能是Swift中的一个错误,因为当你尝试执行以下操作时,编译器会抱怨

struct B: P {
  func test() {}
}
  

' P'需要' B'继承自' UIViewController'

一个不错的解决方案是

class A: UIViewController {
  typealias PViewController = UIViewController & P
  let d: [PViewController] = [PViewController]()

  func m() -> UIViewController? {

      return self.d.first

  }

}

答案 1 :(得分:1)

SKPaymentTransaction

答案 2 :(得分:0)

这可能会起作用,因为编译器不会将类型转换为Self

class A: UIViewController {

    let d: [P] = [P]()

    func m() -> UIViewController? {
        return self.d.first as? UIViewController
    }
}