gpt4 book ai didi

ios - 快速将实例作为对另一个类的引用传递

转载 作者:搜寻专家 更新时间:2023-11-01 06:04:49 25 4
gpt4 key购买 nike

这里是 Swift 新手,我试图将一个类的实例传递给另一个类,但编辑器一直将其标记为错误,这是我的代码:

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,但我想不通如何传递实例。

任何输入都将不胜感激,这样做的目的是让 Handler 类可以调用事件 ViewController 实例的方法。

最佳答案

这与 Swift 中对象的初始化有关。在您的 handler 初始化时,您无权访问 self

要修复它,你可以写

lazy var handler: Handler = Handler(controller: self)

这将初始化推迟到首次访问时。

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.

这意味着并非所有属性都保证在您尝试访问 self 时已初始化,因此您无法访问该对象。

关于ios - 快速将实例作为对另一个类的引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com