almel
almel

Reputation: 7938

Using delegate's methods when delegate is a UIViewController in Swift

I'm not sure if this is an Xcode 6 Swift-specific problem, but here it goes.

I have two classes, MyViewController and UtilViewController. UtilViewController has a delegate property of type UIViewController, because UtilViewController is designed to be used by all of my app's viewcontrollers. It also has a function createOrder() that will only ever be called by MyViewController. Because this function will only ever be called by MyViewController, inside of createOrder() there is a line that calls a function declared by MyViewController, like this

self.delegate!.methodInMyViewController()

However this throws an error in UtilViewController

'UIViewController' does not have a member named 'methodInMyViewController'

How can I preserve the modularity of having a UIViewController delegate, but also be able to call methods from my own viewcontrollers, which are a subclass of UIViewController?

Upvotes: 2

Views: 913

Answers (2)

Martin R
Martin R

Reputation: 539795

Instead of (ab)using the generic delegate of UtilViewController, the createOrder() method could take a closure (callback) parameter. For example:

func createOrder(callWhenDone:()->()) {
    // do stuff ...
    callWhenDone()
}

From within MyViewController, you would call the method as

utilVC.createOrder {
    // called from createOrder()
    self.methodInMyViewController()
}

Upvotes: 0

Connor
Connor

Reputation: 64644

You can cast your delegate as a MyViewController to tell the compiler that it is actually a MyViewController and can call that method.

(self.delegate! as MyViewController).methodInMyViewController()

Since delegate may not always be a MyViewController, you may want to check if it is before casting:

if self.delegate! is MyViewController{
    (self.delegate! as MyViewController).methodInMyViewController()
} 

Upvotes: 1

Related Questions