Codey Codey - 6 months ago 8
Swift Question

Swift - Same protocol for two different classes

I want to use the same protocol for two different classes. It is for two

UIStoryboardSegue
classes, the normal one and the unwind segue. In my first class
GameSegue.swift
, I've declared this protocol

@objc protocol ViewControllerWithBackgroundImage {

var backgroundImage: UIImageView { set get }

}


I use this protocol to have access to the ViewControllers property
backgroundImage
. In the first class
GameSegue.swift
, the normal segue, the
backgroundImage
animates
10 px
up. So in the second class
GameSegueUnwind.swift
, I want to do the same thing backwards, move the background
10 px
down. But to get access to the
backgroundImage
property I need this protocol. Therefore it would be useful, to not declare another protocol, but instead use the same.

Any idea how this is possible?

Answer

In the second class just declare a new delegate variable

class GameSegueUnwind {
     var secondDelegate: ViewControllerWithBackgroundImage?
}

and you will be able to access the function in any other class that conforms to the protocol. Of, course in the conforming class remember to declare it has the delegate handler in the prepare for segue method

destinatonViewController.secondDelegate = self
Comments