简体   繁体   中英

Initialize closure in Swift

I know how to initialize a closure that take no arguments, like this:

class testClass {
    var myClosure: () -> ()

    init(){
        myClosure = {}
    }
}

However, I could not figure out how to initialize closure like this:

var myClosure: (Int) -> ()

How do I do that?

A closure of type (Int) -> () expects one parameter (and Swift will tell you, that the parameter cannot be implicitly ignored).

So if you want to have a closure that takes one parameter, you have to specify this explicitly:

let myClosure: (Int) -> () = { parameter in }

(if you don't need the parameter, you can replace it with a wildcard to ignore it)

let myClosure: (Int) -> () = { _ in }

Alternatively, you can use implicit arguments ( $0 , $1 , etc.), but they only work when you use the parameter somewhere in the closure (eg by assigning it to another variable or passing it as a parameter to a function):

let myClosure: (Int) -> () = { print($0) }

Simple example:

class TestClass {
    var myClosure: (Int) -> ()
    init(){
        func myFunc(_:Int) {}
        self.myClosure = myFunc
    }
}

Or use an anonymous function:

class TestClass {
    var myClosure: (Int) -> ()
    init(){
        self.myClosure = {_ in}
    }
}

Or you could do the initialization as part if the declaration of myClosure :

class TestClass {
    var myClosure : (Int) -> () = {_ in}
    init(){
    }
}

But if you don't have the value of myClosure at initialization time, why not make it an Optional?

class TestClass {
    var myClosure: ((Int) -> ())?
    init(){
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM