How to declare a function with a specific return type that matches the protocol?

In objective-c, I can declare a method with a return type:

-(UIView<MyProtocol> *)someMethod;

In this example, the method returns a UIViewthat matches the protocol MyProtocol.

I want to make something like this quick:

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
}

In general, the delegate should return UIViewwith var " someProperty"

I do not want to define a specific class UIView. I want the user to be able to return any type UIView(as long as it conforms to the protocol)

The syntax I wrote is invalid - how do I write it?

+4
source share
3

:

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
0

Swift . Obj-C Swift. protocol<..., ...>, .

. , , , . , . . .

0

.

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

}

MyClass: MyProtocol.

-2
source

Source: https://habr.com/ru/post/1584862/


All Articles