如何在Swift 3中将函数设置为函数参数
Q:是否可以在Swift 3中将函数作为函数参数传递?如何在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")
}
是这样的可能吗?非常感谢帮助。
是你可以传递一个函数/闭包作为另一个函数的参数。
这是语法
func doSomething(closure:() ->()) {
closure()
}
这里的功能doSomething
接收没有PARAMS和没有返回类型闭包作为参数。
可以调用DoSomething的这个语法
doSomething(closure: { _ in print("Hello world") })
或者使用尾随闭包语法
doSomething {
print("Hello world")
}
闭包不起作用,因为这个代码会在getButton函数被调用的那一刻被调用,而不是一旦按下按钮 –
@DavidSeek,为什么在getButton函数被调用的时候它会被执行? – user28434
如果我在getButton中有一个闭包,它将在函数完成时被调用。但是我需要在按下按钮后调用它 –
函数是迅速一流的,所以你可以像这样通过他们:
func getButton(_ myFunc:() -> Void, _ title: String) {
您需要指定类型的函数,即参数类型的签名和返回类型
谢谢,你的方法和appzYourLife一样好。给他勾号,因为他速度更快。 upvote为您的时间和帮助。谢谢 –
假设
typealias Func =() -> Void
你可以这样做:
func getButton(_ title: String, _ myFunc: Func) {
let deleteButton = MIAlertController.Button(title: title,
type: .cancel,
config: getDestructiveButtonConfig(),
action: {
myFunc()
})
}
甚至:
func getButton(_ title: String, _ myFunc: Func) {
let deleteButton = MIAlertController.Button(title: title,
type: .cancel,
config: getDestructiveButtonConfig(),
action: myFunc
)
}
另外,如果您有没有注意到,我搬到封闭到参数列表的末尾。这样就会让高级的魔法,如:
getButton("X") { … }
,而不是
getButton({ … }, "X")
呃。我喜欢typealias。谢谢!为此赞成 –
你在找这个? '函数类型作为参数类型'在https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html – Santosh
@Santosh你的链接不包括我的问题。我不在寻找关闭或返回值 –
好。实际上我需要一个关闭......我发誓,我已经尝试过。不工作。答案后再次尝试,工作......我的坏。谢谢你或你的时间 –