gpt4 book ai didi

objective-c - 如何在 Swift 中将属性声明为函数?

转载 作者:行者123 更新时间:2023-11-30 14:02:54 25 4
gpt4 key购买 nike

这是我的代码:

import Cocoa

class VC1: NSViewController {
let aFunctionVar ()->Void
}

但是编译器告诉我:“VC1 类没有初始化程序”

根据 Apple Swift iBook 中的 swift 示例,他们的示例如下:

var mathFunction: (Int, Int) -> Int = addTwoInts

但就我而言,我正在尝试创建一个属性变量。目前还不知道变量是什么,所以我无法在那里设置它。有什么帮助吗?

编辑 - 当涉及到简单的字符串/数组/字典类型等时,我已经知道如何使变量可选和惰性。但这是一个函数类型属性变量。它旨在保存 ()->Void 类型的函数。关于如何做到这一点有任何帮助吗?

在 ObjectiveC 中,这可以通过创建如下的 block 属性来完成:

@property (nonatomic, copy)  void (^aFunctionVar)();

最佳答案

projectLaunchData 声明为可选的 var:

import Cocoa

class VC1: NSViewController {
var projectLaunchData: (()->Void)?
}

然后您可以稍后赋值:

func test() {
print("this works")
}

let myVC = VC1()

// assign the function
myVC.projectLaunchData = test

// Call the function using optional chaining. This will safely do nothing
// if projectLaunchData is nil, and call the function if it has been assigned.
// If the function returns a value, it will then be optional because it was
// called with the optional chaining syntax.
myVC.projectLaunchData?()

关于objective-c - 如何在 Swift 中将属性声明为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32772451/

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