Swift:如何在返回类型为self的协议中声明func?

问题描述 投票:-6回答:2

我想做这样的事情(这不是一个编译的代码,因为这只是我想要在最后收到的例子):

protocol AP {
 class func perform() -> self
}

class A: UIViewController, AP {
//
...
//
 class func perform() -> A {
   return A()
 }
}

我需要这个作为结果let vc = A.perform(),意味着我需要协议,将返回自我类型的订阅者

我怎么能这样做?

ios swift xcode swift4.2
2个回答
4
投票

我认为这应该做你想要的:

protocol AP {
    associatedtype T

    static func perform() -> T
}

class A: UIViewController, AP {
    //
    ...
    //
    class func perform() -> A {
        return A()
    }
}

您现在可以按照以下方式执行此操作:

let vc = A.perform()

0
投票
  1. 在协议中使用静态方法而不是类方法。
  2. 给出一个返回类型。自我不是回归类型。 protocol AP { func perform() -> () } class A: UIViewController, AP { // ... // func perform() { } }
© www.soinside.com 2019 - 2024. All rights reserved.