Closure not called inside object - swift

I am trying to run this simple example using a closure for learning purpose, but doesn't seem to work as I expected:
class Test {
var callback: ((_ value: Int) -> Void)?
func perform() {
callback
}
}
let t = Test()
t.callback = { _ in
print("Test")
}
t.perform()
I was expected that "Test" will get printed, but apparently it's not. Can someone point what the issue is ?

Compiling the code reveals the error:
error: expression resolves to an unused l-value
callback
^~~~~~~~
callback is just the (optional) closure, not a call to the closure.
Apparently the Playground does not complain about the unused expression.
Calling the closure with some argument fixes the problem:
func perform() {
callback?(5)
}

Related

Closure forwarding without evaluating

I'm writing a logging function that also calls a CocoaLumberjack function (yes, I know about custom loggers and chose not to use it). My function is using a forward, but I have a question about how the 'forwarding' works.
Here's my functions:
public func MyLogDebug(_ message: #autoclosure () -> String) {
// some code
MyLogMessage(message(), .debug)
}
public func MyLogMessage(_ message: #autoclosure () -> String, flag: DDLogFlag) {
// some code
if(myLogLevel.rawValue & flag.rawValue != 0) {
DDLogDebug(message())
}
}
My question is about the MyLogMessage(message(), .debug) function call. I know that avoiding string concatenation is really helpful for performance with logs, and I can see that inside MyLogMessage the string closure is only ran if the log level is passed. However, it look like in MyLogDebug the closure is also being evaluated.
I don't want to run the closure in MyLogDebug, so I tried to change it to MyLogMessage(message, .debug), but xcode gives me an error: Add () to forward #autoclosure parameter.
Will my code above evaluate the closure inside MyLogDebug? If so, is there another way to forward the closure parameter without evaluating it?
Will my code above evaluate the closure in MyLogDebug?
No. The call message() will be wrapped in a closure by the #autoclosure in MyLogMessage and only evaluated when message() is subsequently called in MyLogMessage.
Here is a little standalone example to play with:
func DDLogDebug(_ message: String) {
print("in DDLogDebug")
print(message)
print("leaving DDLogDebug")
}
public func MyLogDebug(_ message: #autoclosure () -> String) {
// some code
print("in MyLogDebug")
MyLogMessage(message(), flag: true)
print("leaving MyLogDebug")
}
public func MyLogMessage(_ message: #autoclosure () -> String, flag: Bool) {
// some code
print("in MyLogMessage")
if (flag) {
DDLogDebug(message())
}
print("leaving MyLogMessage")
}
MyLogDebug({ print("evaluated"); return "error message" }())
Output:
in MyLogDebug
in MyLogMessage
evaluated
in DDLogDebug
error message
leaving DDLogDebug
leaving MyLogMessage
leaving MyLogDebug
Note that the initial closure passed to MyLogDebug isn't evaluated until the DDLogDebug(message()) in MyLogMessage().
If you change the flag to false in the call to MyLogMessage(), the initial closure will never be evaluated.

What is the meaning of var something: (() -> Void)? in Swift [duplicate]

I'm trying to declare an argument in Swift that takes an optional closure. The function I have declared looks like this:
class Promise {
func then(onFulfilled: ()->(), onReject: ()->()?){
if let callableRjector = onReject {
// do stuff!
}
}
}
But Swift complains that "Bound value in a conditional must be an Optional type" where the "if let" is declared.
You should enclose the optional closure in parentheses. This will properly scope the ? operator.
func then(onFulfilled: ()->(), onReject: (()->())?){
if let callableRjector = onReject {
// do stuff!
}
}
To make the code even shorter we can use nil as default value for onReject parameter and optional chaining ?() when calling it:
func then(onFulfilled: ()->(), onReject: (()->())? = nil) {
onReject?()
}
This way we can omit onReject parameter when we call then function.
then({ /* on fulfilled */ })
We can also use trailing closure syntax to pass onReject parameter into then function:
then({ /* on fulfilled */ }) {
// ... on reject
}
Here is a blog post about it.
Since I assume, that this "optional" closure should simply do nothing, you could use a parameter with an empty closure as default value:
func then(onFulfilled: ()->(), onReject: ()->() = {}){
// now you can call your closures
onFulfilled()
onReject()
}
this function can now be called with or without the onReject callback
then({ ... })
then({ ... }, onReject: { ... })
No need for Swift's awesome Optionals? here!
Maybe it's a cleaner way. Specially when the closure has complicated parameters.
typealias SimpleCallBack = () -> ()
class Promise {
func then(onFulfilled: SimpleCallBack, onReject: SimpleCallBack?){
if let callableRjector = onReject {
// do stuff!
}
}
}
As an alternative to creating a TypeAlias or using well-placed parentheses, there's always Swift's Optional type itself.
It can be used just like your typical Java (or in this case Swift) Generic Array syntax Optional<() -> ()>
OR in context:
func callAClosure(firstClosure: () -> (), secondClosure: Optional<() -> ()> {
if let secondClosure = secondClosure {
secondClosure()
}
else { firstClosure() }
}
I find this to be fairly clean. As a bonus, in the context of SwiftUI where generics can be common, like struct CommonList<T: View>: View then you don't have to create a typealias that only gets used once (commonly the init function for that struct). Instead, you make one simple optional closure parameter, and you're all done!
Hopefully this helps anyone that runs into the issue and happy coding!

Swift optional escaping closure

Compiler error Closure use of non-escaping parameter 'completion' may allow it to escape, Which make sense because it will be called after the function return.
func sync(completion:(()->())) {
self.remoteConfig.fetch(withExpirationDuration: TimeInterval(expirationDuration)) { (status, error) -> Void in
completion()
}
}
But if I make closure optional then no compiler error, Why is that? closure can still be called after the function returns.
func sync(completion:(()->())?) {
self.remoteConfig.fetch(withExpirationDuration: TimeInterval(expirationDuration)) { (status, error) -> Void in
completion?()
}
}
Wrapping a closure in an Optional automatically marks it escaping. It's technically already "escaped" by being embedded into an enum (the Optional).
Clarification:
For understanding the case, implementing the following code would be useful:
typealias completion = () -> ()
enum CompletionHandler {
case success
case failure
static var handler: completion {
get { return { } }
set { }
}
}
func doSomething(handlerParameter: completion) {
let chObject = CompletionHandler.handler = handlerParameter
}
At the first look, this code seems to be legal, but it's not! you would get compile-time error complaining:
error: assigning non-escaping
parameter 'handlerParameter' to an #escaping closure
let chObject = CompletionHandler.handler = handlerParameter
with a note that:
note: parameter 'handlerParameter' is implicitly non-escaping func
doSomething(handlerParameter: completion) {
Why is that? the assumption is that the code snippet has nothing to do with the #escaping...
Actually, since Swift 3 has been released, the closure will be "escaped" if it's declared in enum, struct or class by default.
As a reference, there are bugs reported related to this issue:
Optional closure type is always considered #escaping.
#escaping failing on optional blocks.
Although they might not 100% related to this case, the assignee comments are clearly describe the case:
First comment:
The actual issue here is that optional closures are implicitly
#escaping right now.
Second comment:
That is unfortunately the case for Swift 3. Here are the semantics for
escaping in Swift 3:
1) Closures in function parameter position are
non-escaping by default
2) All other closures are escaping
Thus, all generic type argument closures, such as Array and Optional, are escaping.
Obviously, Optional is enum.
Also -as mentioned above-, the same behavior would be applicable for the classes and structs:
Class Case:
typealias completion = () -> ()
class CompletionHandler {
var handler: () -> ()
init(handler: () -> ()) {
self.handler = handler
}
}
func doSomething(handlerParameter: completion) {
let chObject = CompletionHandler(handler: handlerParameter)
}
Struct Case:
typealias completion = () -> ()
struct CompletionHandler {
var handler: completion
}
func doSomething(handlerParameter: completion) {
let chObject = CompletionHandler(handler: handlerParameter)
}
The two above code snippets would leads to the same output (compile-time error).
For fixing the case, you would need to let the function signature to be:
func doSomething( handlerParameter: #escaping completion)
Back to the Main Question:
Since you are expecting that you have to let the completion:(()->())? to be escaped, that would automatically done -as described above-.

Trouble with non-escaping closures in Swift 3

I have an extension Array in the form of:
extension Array
{
private func someFunction(someClosure: (() -> Int)?)
{
// Do Something
}
func someOtherFunction(someOtherClosure: () -> Int)
{
someFunction(someClosure: someOtherClosure)
}
}
But I'm getting the error: Passing non-escaping parameter 'someOtherClosure' to function expecting an #escaping closure.
Both closures are indeed non-escaping (by default), and explicitly adding #noescape to someFunction yields a warning indicating that this is the default in Swift 3.1.
Any idea why I'm getting this error?
-- UPDATE --
Screenshot attached:
Optional closures are always escaping.
Why is that? That's because the optional (which is an enum) wraps the closure and internally saves it.
There is an excellent article about the quirks of #escaping here.
As already said, Optional closures are escaping. An addition though:
Swift 3.1 has a withoutActuallyEscaping helper function that can be useful here. It marks a closure escaping only for its use inside a passed closure, so that you don't have to expose the escaping attribute to the function signature.
Can be used like this:
extension Array {
private func someFunction(someClosure: (() -> Int)?) {
someClosure?()
}
func someOtherFunction(someOtherClosure: () -> Int) {
withoutActuallyEscaping(someOtherClosure) {
someFunction(someClosure: $0)
}
}
}
let x = [1, 2, 3]
x.someOtherFunction(someOtherClosure: { return 1 })
Hope this is helpful!
The problem is that optionals (in this case (()-> Int)?) are an Enum which capture their value. If that value is a function, it must be used with #escaping because it is indeed captured by the optional.
In your case it gets tricky because the closure captured by the optional automatically captures another closure. So someOtherClosure has to be marked #escaping as well.
You can test the following code in a playground to confirm this:
extension Array
{
private func someFunction(someClosure: () -> Int)
{
// Do Something
}
func someOtherFunction(someOtherClosure: () -> Int)
{
someFunction(someClosure: someOtherClosure)
}
}
let f: ()->Int = { return 42 }
[].someOtherFunction(someOtherClosure: f)

IOs Swift : How does completion closure work

Can anybody explain me, how does this code work
private func viewWillTransition(completion:(() -> Void)?)
{
if completion != nil
{
completion!()
}
}
This is a basic scheme of implementing callbacks in Swift.
The function takes parameter completion of type () -> Void)?, meaning "an optional closure taking no parameters and not returning a value."
The code inside tests the optional value of closure for nil. If it is not nil, the code unwraps it with !, and makes a call.
A somewhat more idiomatic way of implementing this in Swift is with if let construct:
private func viewWillTransition(completion:(() -> Void)?) {
if let nonEmptyCompletion = completion {
nonEmptyCompletion()
}
}