Pass the instance as a reference to another class in swift

徘徊边缘 提交于 2021-01-06 04:34:39

问题


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.


回答1:


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)
}



回答2:


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.



来源:https://stackoverflow.com/questions/40349050/pass-the-instance-as-a-reference-to-another-class-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!