Reputation: 145
I've been writing in Kotlin for a while, and I get used to use next pattern:
variable.addSomething(object: TargetType() { ...code... })
or
var variable = object: TargetType() { ...code... }
(if i'm not missing something)
Is it possible to somehow use this pattern in Swift ? And how is it called ? :)
Edit: What I actually want to do - to store preconfigured RxSwift.SingleEvent in a let / var inside object and reuse it later multiple times.
In code, as I imagine, it should look like that:
private var observer = SingleEvent<Response>(ok_callback, error_callback) {
override success(el: Element) {
ok_callback(el)
super.success(el)
}
override error(er: Error) {
self.onErrorRetry(er, callback)
}
}
And if retry after some magic works - simply call my callback and return back :)
Upvotes: 2
Views: 1263
Reputation: 31655
Its seems to be trailing closure. Adapted from Swift programming language - Closures:
If you need to pass a closure expression to a function as the function’s final argument and the closure expression is long, it can be useful to write it as a trailing closure instead. A trailing closure is written after the function call’s parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don’t write the argument label for the closure as part of the function call.
Let's code it:
Simply, all you have to do is just to create a function which its last argument is a closure:
func doSomething(firstParameter: Any, closure: () -> Void) { }
thus you could call it as:
doSomething(firstParameter: "whatever") {
// ...
}
Nothing special goes here, it is a cool feature from the Swift language to "trail" closure
parameter if its the last one in the function signature.
In case of initialization, it is almost the same:
struct MyObject {
init(firstParameter: Any, closure: () -> Void) { }
}
let variable = MyObject(firstParameter: "whatever") { }
Certainly, this pattern is followed by many other functions in the language, but here is an example of the merge
method for the Dictionary, you could recognize how you could type it in more than one way as mentioned in the answers of: Map Dictionary Keys to add values - Swift.
Update:
If you are aiming to use it as constant/variable -to be passed for a function for example-, you could do it like this:
let variable: (String) -> Void = { name in
print("The name is: \(name)!")
}
At this point, variable
type is (String) -> Void
which means that its a constant that could be passed somewhere else; Consider the following method:
func doSomething(closure: (String) -> Void) {
closure("Nikita")
}
Because doSomething
takes a parameter of type (String) -> Void
, you could do:
doSomething(closure: variable) // The name is: Nikita!
instead of calling it as:
doSomething { name in
print("The name is: \(name)!")
}
which prevents the boilerplate code.
Upvotes: 1