How can I make a function complete before calling others in an IBAction?
Something like this:
func verify(myText: String, completion: (bool: Bool)->()) {
var result = true
// some code that fetches a string "orlando" on the server
if myText == "orlando" {
result = false
}
completion(bool: result)
}
And you call it in your IBAction like this, with a trailing closure:
verify(myTextField.text!) { (bool) in
if bool {
// condition in `verify()` is true
} else {
// condition in `verify()` is false
}
}
Note: where you say "some code that fetches a string "orlando" on the server", be careful to not set the new completion
after the async call, otherwise you would still experience the same issue... The completion should be used in the same scope as the async call result.
How to Auto call an @IBAction function
You can either change the signature of the IBAction by making its parameter an Optional like this:
@IBAction func doSomeTask(sender: UIButton?) {
// code
}
and then call it with nil as an argument:
doSomeTask(nil)
Or you can use the IBAction as a wrapper for the real function:
func doSomeTaskForButton() {
// ...
}
@IBAction func doSomeTask(sender: UIButton) {
doSomeTaskForButton()
}
meaning you can then call doSomeTaskForButton()
from wherever you want.
How Can I Make Sure This Function Completes Before I Interpret The Response?
The problem in your code is the line here:
task.resume()
finished(apiResult)
You should remove the call to the finished
completion handler, since that one should be called in the placed where it is already placed, after getting the response.
Another improvement suggestion to you would be to simplify your field validation code to use guard
statements.
What's the best way to call an IBAction from with-in the code?
The proper way is either:
- [self functionToBeCalled:nil]
To pass a nil sender, indicating that it wasn't called through the usual framework.
OR
- [self functionToBeCalled:self]
To pass yourself as the sender, which is also correct.
Which one to chose depends on what exactly the function does, and what it expects the sender to be.
Related Topics
Swift/Cloudkit: After Record Changed, Upload Triggers "Service Record Changed"
How to Set Avaudioengine Input and Output Devices (Swift/Macos)
Protocol Can Only Be Used as a Generic Constraint
Swift: Generics and Type Constraints, Strange Behavior
Xcode Playgrounds Shared Directory Not Working
Nsinvocationoperation' Is Unavailable in Xcode 6.1
Set Custom Uiview Frame in Uiviewrepresentable Swiftui
Swift Use Unicode Character in Localization.Strings
Swiftui View Does Not Updated When Observedobject Changed
Skspritenode Gets Hidden Below Parent Node
Phase 1 and Phase 2 Initialization in Swift
Best Way to Avoid Capturing a Copy of the Value in Closure
How to Respond with an Image Using Vapor
Swift Tdd & Async Urlsession - How to Test
Sf Symbols Hierarchical, Palette, and Multicolor Rendering Mode Colors