0

New to Swift -- apologies. Suppose fetchString(@escaping completion: (String) -> Void).

How can I store the closure value response in str?

var str: String  // suppose this is initialized
API.fetchString() { response in
    str = response // or something similar like append
}
return str
nonamorando
  • 1,556
  • 2
  • 14
  • 33
  • closure/block is executed asynchronously, as it is a API call, but return statement will be executed synchronously hence str value will be returned even before `closure` could execute, hence you feel like str is not updated, – Sandeep Bhandari Jan 18 '21 at 08:21
  • Have a look at https://stackoverflow.com/q/27081062/1187415 or these related Q&As: https://stackoverflow.com/search?q=%5Bswift%5D+return+from+asynchronous – Martin R Jan 18 '21 at 08:21
  • Thanks, wasn't aware these calls weren't on the main thread. – nonamorando Jan 19 '21 at 05:41

0 Answers0