Fast protocol of a certain class

I want to define a type variable UIViewControllerthat matches P1.

Question:

  • Should I change the protocol or type v1?
  • How can I do it?

The code:

protocol P1 {

    func f1();
}


var v1 : P1 //But needs to be a UIViewController which conforms to `P1`
+4
source share
4 answers

In Swift 4, you can use the new and sign to create a variable that matches the protocol and class, the syntax is as follows:

let vc: UIViewController & P1
+5
source

Starting with Swift 4:

Thanks to SE-0156 :

&, AnyObject, . Objective-C :

AnyObject & Protocol1 & Protocol2
Base & Protocol

Objective-C, , Protocol1 Protocol2, Base, Protocol.

.. :

var v1 : UIViewController & P1 // UIViewController which conforms to `P1`

Swift 4:

. v1 UIViewController, P1, casting (as), .

, , . :

func testGeneric<T: UIViewController where T: P1>(input: T) {
    input.f1()
}

, , , , :

protocol Delegate: class { 
    func doDelegate()
}

class Controller { 
    func doController() {
        print("Controller")
    }
}

class ConcreteController: Controller, Delegate {
    func doDelegate() {
        print("Delegate")
    }
}

class View {
    private weak var controller: Controller? = nil
    private weak var delegate: Delegate? = nil

    func setDelegateController<T: Controller where T: Delegate>(delegateController: T?) {
        controller = delegateController
        delegate = delegateController
    }

    func test() {
        controller?.doController()
        delegate?.doDelegate()
    }
}

:

let view = View()
let controller = ConcreteController()

view.setDelegateController(controller)

view.test()  // This will print:
             // Controller
             // Delegate
+6

You can create another empty protocol, restrict UIViewControllerit to this protocol, and then use the directive protocol<>to combine the two protocols into one type:

protocol UIViewControllerType {} // empty
protocol P1 { ... }

// Make sure only UIViewController adopts UIViewControllerType
extension UIViewController: UIViewControllerType {}

extension UITableViewController: P1 {}

// This works:
var v1: protocol<UIViewControllerType, P1> = UITableViewController()

// This doesn't:
var v2: protocol<UIViewControllerType, P1> = UIViewController()
+1
source

How about this way:

protocol P1 {
    func f1()
    func getVC() -> UIViewController
}

class MyVC : UIViewController, P1 {

    func f1() {
        // do stuff
    }

    func getVC() -> UIViewController {
        return self
    }
}

var v1 : P1 = MyVC()

v1.getVC() // do UIViewController related things
0
source

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


All Articles