簡體   English   中英

如何聲明具有符合協議的具體返回類型的函數?

[英]How to declare a function with a concrete return type conforming to a protocol?

編輯:這個問題是在swift添加some關鍵字之前寫的,使其過時

在objective-c中,我可以聲明一個帶有返回類型的方法:

-(UIView<MyProtocol> *)someMethod;

在這個例子中該方法返回一個UIView符合的協議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“ someProperty ”的UIView

希望定義一個具體UIView類。 我希望用戶能夠返回任何類型的UIView (只要它符合協議)

我寫的語法無效 - 我應該怎么寫?

您可以只使用協議作為類型:

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

這在 Swift 中是不可能的。 並非 Obj-C 中所有可能的東西都必須在 Swift 中成為可能。 創建類型要求時,您只能使用protocol<..., ...>語法組合協議protocol<..., ...>但不能組合類和協議。

從技術上講,這應該有利於您的架構。 您可能會找到一種解決方法,但我建議您不要這樣做。 避免將類與協議結合是有原因的,因為接口更難處理。 大多數 OOP 語言沒有這種語法。 許多常用語言甚至沒有組合協議的語法。

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
    }
}

問題是在swift-ui之前寫的

"some" 關鍵字通過允許從函數返回不透明類型解決了這個問題

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

下面是一種方法。

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

}

您可以在沒有可選類型的情況下使用 MyClass: MyProtocol。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM