Reputation: 1140
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.
Upvotes: 1
Views: 4194
Reputation: 2745
This has to do with initialization of objects in Swift. You don't have access to self
at the time your handler
is being initialized.
To fix it, you could write
lazy var handler: Handler = Handler(controller: self)
This defers initialization to the time when it's first accessed.
Documentation on two-phase initialization:
Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
This means that not all properties are guaranteed to have been initialized at the time you try to access self
, hence you're prevented from accessing the object.
Upvotes: 5
Reputation: 5695
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)
}
Upvotes: 3