【发布时间】:2016-11-07 14:41:16
【问题描述】:
问:是否可以在 Swift 3 中将函数作为函数参数传递?
为了重构我的代码,我想要一个全局函数。在这个函数的最后,有一个自定义按钮,它有一个action 参数。
let deleteButton = MIAlertController.Button(title: "cancel",
type: .cancel,
config: getDestructiveButtonConfig(),
action: {
print("completed")
})
我想做的就是设置一个以函数为参数的全局函数。
MyGlobalStuff.swift
...
func getButton(_ myFunc: func, _ title: String) {
let deleteButton = MIAlertController.Button(title: title,
type: .cancel,
config: getDestructiveButtonConfig(),
action: {
myFunc // call here the function pass by argument
})
}
由getButton(..) 使用同一类中的传递函数调用。
MyViewController.swift
...
getButton(myPrintFunc, "cancel")
func myPrintFunc() {
print("completed")
}
这样的事情可能吗?非常感谢您的帮助。
【问题讨论】:
-
你在找这个吗?
Function Types as Parameter Typesin developer.apple.com/library/content/documentation/Swift/… -
@Santosh 您的链接不涵盖我的问题。我不是在寻找关闭或返回值
-
好吧。实际上我需要一个关闭...我发誓,我以前尝试过。不工作。答案后再次尝试,工作......我的错。谢谢你或你的时间
标签: swift