如何使用符合协议的具体返回类型声明函数?

时间:2015-04-27 09:16:00

标签: ios swift protocols generics

在objective-c中,我可以声明一个返回类型的方法:

-(UIView<MyProtocol> *)someMethod;

在此示例中,该方法返回符合协议UIView的{​​{1}}。

我想在swift中做类似的事情:

MyProtocol

一般情况下 - 代理人应返回protocol MyProtocol { var someProperty : Int {get set} } protocol MyDelegate { func someMethod() -> UIView : MyProtocol // the view should conform to the protocol - I don't care what kind of view it is - I don't want to define a specific type of view } ,其中包含var“UIView

想要定义具体的someProperty类。 我希望用户能够返回任何类型的UIView(只要符合协议)

我写的语法无效 - 我该怎么写呢?

5 个答案:

答案 0 :(得分:0)

您可以将协议用作类型:

protocol MyDelegate {
    func someMethod() -> MyProtocol
}

并像这样使用它:

protocol MyProtocol {
    var someProperty : Int {get set}
}

class CustomView: UIView, MyProtocol {
    var someProperty = 2
}

protocol MyDelegate {
    func someMethod() -> MyProtocol
}

struct Delegate: MyDelegate {
    func someMethod() -> MyProtocol {
        return CustomView()
    }
}

let delegate = Delegate()
let view = delegate.someMethod()
let property = view.someProperty // property = 2

答案 1 :(得分:0)

这在Swift中是不可能的。在Swift中,Obj-C中不可能有所有可能。创建类型要求时,您只能使用protocol<..., ...>语法组合协议,但无法将类和协议组合在一起。

从技术上讲,这应该对您的架构有益。你可以找到一个解决方法,但我会反对它。有理由避免将类与协议组合,因为接口更难以处理。大多数OOP语言都没有这种语法。许多常用语言甚至没有语法来组合协议。

答案 2 :(得分:0)

protocol MyProtocol {
  var someProperty : Int {get set}
}

protocol MyDelegate {
  func someMethod<T: UIView & MyProtocol>() -> T // the view should conform to the protocol - I don't care what kind of view it is - I don't want to define a specific type of view
}

class MyDelegateTestView : UIView, MyProtocol {
    var someProperty: Int = 10
}

class MyDelegateTestClass : MyDelegate {
    func someMethod<T>() -> T where T : UIView, T : MyProtocol {
        return MyDelegateTestView() as! T
    }
}

答案 3 :(得分:0)

问题是在 swift-ui 之前写的

“some”关键字通过允许从函数返回不透明类型解决了这个问题

protocol MyDelegate {
  func someMethod() -> some MyProtocol 
}

答案 4 :(得分:-2)

以下是一种方法。

func myMethod(string: String) -> MyClass:MyProtocol? {

}

您可以使用不带可选类型的MyClass:MyProtocol。