[英]How to declare a property as a function in Swift?
這是我的代碼:
import Cocoa
class VC1: NSViewController {
let aFunctionVar ()->Void
}
但是編譯器告訴我:“ VC1類沒有初始化程序”
根據Apple Swift iBook中的swift示例,他們的示例如下:
var mathFunction: (Int, Int) -> Int = addTwoInts
但就我而言,我正在嘗試創建一個屬性變量。 目前尚不清楚該變量將是什么,因此我無法在此處進行設置。 有什么幫助嗎?
編輯 -當涉及簡單的String / Array / Dictionary類型等時,我已經知道如何使變量成為可選變量和惰性變量。但這是一個函數類型屬性變量。 它意味着要持有()->Void
類型的函數。 有什么幫助嗎?
在ObjectiveC中,可以通過制作如下的block屬性來完成:
@property (nonatomic, copy) void (^aFunctionVar)();
如果在設置對象之后知道該值,則可以使用惰性變量:
class LazyTester {
lazy var someLazyString: String = {
return "So sleepy"
}()
}
var myLazyTester = LazyTester()
myLazyTester.someLazyString
編譯器給您該錯誤,因為您正在定義一個必需的存儲變量projectLaunchData
,但沒有給它賦值。 如果您知道初始化時的變量值,則可以在初始化時進行設置。
將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?()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.