CherryBeginner CherryBeginner - 1 year ago 57
Swift Question

Swift running 3 functions one after another

I was wondering if anyone could help me with running 3 functions that rely on information from the previous function to work.
This is the code I found from a previous post on how to get 2 to work:

func firstTask(completion: (success: Bool) -> Void) {
// Do something

// Call completion, when finished, success or faliure
completion(success: true)

//And use your completion block like this:
firstTask { (success) -> Void in
if success {
// do second task if success

But where would the 3rd function go if you want it to run after the second one completes?
Sorry if this a really basic question, but I'm still getting the hang of programming and Swift.

Thanks for the help!

Answer Source

It's best to return the results as a return value, and chain functions together using intermediate variables.

Try to avoid overusing completion handlers. They can make code exceptionally hard to navigate. Prefer return values whenever possible.

func produceASCIIHexCodes() -> [UInt8] {
    return [0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21]

func convertToUnicodeScalars(hexCodes: [UInt8]) -> [UnicodeScalar] {

func convertToCharacters(unicodeScalars: [UnicodeScalar]) -> [Character] {

func createString(fromCharacters characters: [Character]) -> String {
    return String(characters)

func display(string: String) {

let hexCodes = produceASCIIHexCodes()
let unicodeScalars = convertToUnicodeScalars(hexCodes: hexCodes)
let characters = convertToCharacters(unicodeScalars: unicodeScalars)
let string = createString(fromCharacters: characters)
display(string: string)