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?
Don't specify the type again when assigning a value to myClosure . Specifying the type is only necessary when creating the variable. Instead, just assign the closure to the variable: myClosure = { _ in } . @Palle thank you again, but you better provide code that will compile when i try to put it in init(){} method.
Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
You see, the closure starts and ends with the braces, which means we can't put code outside those braces to control parameters or return value. So, Swift has a neat workaround: we can put that same information inside the braces, like this: let sayHello = { (name: String) -> String in "Hi \(name)!" }
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
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(){
}
}
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 (e.g. by assigning it to another variable or passing it as a parameter to a function):
let myClosure: (Int) -> () = { print($0) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With