Swift函数参数默认值

时间:2016-09-12 03:50:52

标签: ios swift function parameters swift2

我正在创建一个包装函数,用于在swift中显示警报视图。

这是当前的工作代码,但目前我还没有通过功能来完成"完成" .presentViewController函数中的参数

func showAlert(viewClass: UIViewController, title: String, message: String)
{
    // Just making things easy to read
    let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))

    // Notice the nil being passed to "completion", this is what I want to change
    viewClass.presentViewController(alertController, animated: true, completion: nil)
}

我希望能够将一个函数传递给showAlert,并在完成时调用该函数,但我希望该参数是可选的,所以默认情况下它是nil

// Not working, but this is the idea
func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void?) = nil)
{
    let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))

    viewClass.presentViewController(alertController, animated: true, completion: action)
}

我得到以下内容,无法转换类型'()'预期参数类型'() - >无效'?

修改

感谢Rob,它现在在语法上运行但是当我尝试调用它时,我得到:

无法转换类型'()'的值预期参数类型'(() - > Void)?'

以下是我如何称呼它

showAlert(self, title: "Time", message: "10 Seconds", action: test())

test() {
    print("Hello")

}

1 个答案:

答案 0 :(得分:2)

您将问号放在错误的位置。这有效:

// go build -ldflags -H=windowsgui
package main

import "fmt"
import "os"
import "syscall"

func main() {
    modkernel32 := syscall.NewLazyDLL("kernel32.dll")
    procAllocConsole := modkernel32.NewProc("AllocConsole")
    r0, r1, err0 := syscall.Syscall(procAllocConsole.Addr(), 0, 0, 0, 0)
    if r0 == 0 { // Allocation failed, probably process already has a console
        fmt.Printf("Could not allocate console: %s. Check build flags..", err0)
        os.Exit(1)
    }
    hout, err1 := syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE)
    hin, err2 := syscall.GetStdHandle(syscall.STD_INPUT_HANDLE)
    if err1 != nil || err2 != nil { // nowhere to print the error
        os.Exit(2)
    }
    os.Stdout = os.NewFile(uintptr(hout), "/dev/stdout")
    os.Stdin = os.NewFile(uintptr(hin), "/dev/stdin")
    fmt.Printf("Hello!\nResult of console allocation: ")
    fmt.Printf("r0=%d,r1=%d,err=%s\nFor Goodbye press Enter..", r0, r1, err0)
    var s string
    fmt.Scanln(&s)
    os.Exit(0)
}

当你打电话时,不要包括括号:

// wrong: action: (() -> Void?) = nil
// right: action: (() -> Void)? = nil

func showAlert(viewClass: UIViewController, title: String, message: String, action: (() -> Void)? = nil)
{
    ...
}