将实例作为对 swift 中另一个类的引用传递 [英] Pass the instance as a reference to another class in swift
问题描述
这里是 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
}
}
行 let handler: Handler = Handler(controller: self)
给出以下错误:
Cannot convert value of type '(NSObject) -> () -> ViewController' to expected argument type 'ViewController'
我来自 java、c#、php 背景,据我所知 self
相当于这些语言中的 this
,但我无法弄清楚如何传递实例.
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.
任何输入都将不胜感激,这样做的目的是让 Handler 类可以调用活动 ViewController 实例的方法.
Any input would be appreciated, the objective of doing this is so the Handler class can call methods of the active ViewController instance.
推荐答案
ViewController 对象尚未初始化.这就是它的原因.您可以简单地将处理程序设为可选的 var
并在 viewDidLoad()
函数
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)
}
这篇关于将实例作为对 swift 中另一个类的引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!