Roberto Arosemena Roberto Arosemena - 1 month ago 7
iOS Question

Pass the instance as a reference to another class in swift

Swift newbie here, I'm trying to pass the instance of a class to another class yet the editor keeps marking it as a mistake, this is the code i have:

ViewController.swift


import UIKit
import Foundation

class ViewController: UIViewController {

let handler: Handler = Handler(controller: self)

override func viewDidLoad() {
super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

}


Handler.swift


import Foundation

class Handler
{
var controller: ViewController? = nil

init(controller: ViewController) {
self.controller = controller
}
}


The line
let handler: Handler = Handler(controller: self)
gives the following error:

Cannot convert value of type '(NSObject) -> () -> ViewController' to expected argument type 'ViewController'


I come from a java, c#, php background and as far as i know
self
is the equivalent of
this
on those languages, yet I can't figure out how to pass the instance.

Any input would be appreciated, the objective of doing this is so the Handler class can call methods of the active ViewController instance.

Answer

The ViewController object is not initialized yet. That's the reason for it. You can simply make handler an optional var and initialize it inside viewDidLoad() function

var handler: Handler? // optional variable

override func viewDidLoad() {
    super.viewDidLoad()

    handler = Handler(controller: self)
}
Comments