0

I have a function in swift to return a string from array, if the array has value return directly, if not I need load it from server and return the value from callback, I don't know how to do it, something like

func getValue(idx: Int)->string {
    if arrayValue.count <= 0 {
        callbackfunc() { arrayValue in 
        return arrayValue[idx]
       }
    } else {
      return arrayValue[idx]
    }
}

but it is impossible to return from callback, any help? thank you very much

2 Answers 2

1

Add a completion handler:

func getValue(idx: Int, completion: @escaping (String) -> Void) {
    if arrayValue.count <= 0 {
       callbackfunc() { arrayValue in 
          completion(arrayValue[idx])
       }
    } else {
      completion(arrayValue[idx])
    }
}

And call it:

getValue(idx: 2) { result in
    print(result)
}
Sign up to request clarification or add additional context in comments.

Comments

0

As you have found out you cannot directly return a value from a closure. Therefore you need to handle the returned data within the callback. This can be as complex as needs be, but for a simple example you could just pass the data back to an underlying method.

Depending on what else the app might be doing during the time the callback is running, you may need to be careful how you update this data to make it thread-safe. As a simple precaution it's probably worth performing the update on the main thread:

func getValue(idx: Int)->string {
    if arrayValue.count <= 0 {
        callbackfunc() { [weak self] arrayValue in 
           DispatchQueue.main.async {
              self.processReturnedData(arrayValue[idx])
           }
       }
    } else {
      return arrayValue[idx]
    }
}

func processReturnedData(_ idx: IDXType) {
   //do something with the data
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.