-1

I want to assign value to a variable inside the if expression.

func message() -> Int?{
  var y = "" 
  if x.Sender(msg, reply: { message in
      replyFunc {
          if message.command == .success {
               y = "Hello World"
               print(y) //It prints hello world
          }   
       }   
  }) {   
      print("Error") 
  }
  return y //Here I don't get Hello World
}

I want to assign 'y' from inside the expression.

Edit: This issue is of asynchronous callback and please refer to Matt's comment for the tutorial.

curiously77
  • 225
  • 1
  • 4
  • 24

2 Answers2

2

This is a good question a lot of new to swift/async programmers fall.

Either Sender or ReplyFunc are async functions: Meaning they will open a new thread(for simplicity sake) and do the assignment there. Two things will happen in parallel and you cant know which going to be first. Because Entering closure and then entering another closure is more work in reality order of execution might be:

  • First: return y
  • Second: y = "whatever string you had to assign"

Solution: Return completion closure.

    func message(completion: (String)->()) {
        if x.Sender(msg, reply: { message in
            replyFunc {
                if message.command == .success {
                    completion("Hello World")//It send hello world
                } else {
                    completion("Failure")
                }
            }
        }) {
            completion("Error")
        }
    }

Consuming Y:

    message { y in
        print(y) // here is my "Hello World" or "Error" when error
    }

NOTE: You must always, with all flows, run completion, this is a best practice.

Moris Kramer
  • 1,490
  • 1
  • 12
  • 13
-3
func someMethod() {
    _ = message()
}

func handleReply(message: SomeType) {
    if message.command = .success {
        y = "Hello World"
    }
}

func message() -> Int?{
      var y = "" 
      if x.Sender(msg, reply: { message in
          replyFunc {
              handleReply(message)
           }   
      }) {   
          print("Error") 
      }
      return y //Here I don't get Hello World
    }
Loren Rogers
  • 325
  • 3
  • 13