← back to the blog


Defer Swift 5.1 / 5 with example

Posted on November 23rd, 2019 in Swift by George

 

This function would not allow the messages from Block 1 to be executed unless the school is open. 

Take a look to see how defer handles the control flow of the function.

 

var schoolIsOpen = false;
let kidsInSchool = ["Dan", "Mark" , "Lori", "Mina"];

func childInSchool(_ child: String) -> String {
    
    schoolIsOpen = true;
    
    var text = "Error school is closed";
    
    //Defere in usage, you will see that the messages from Block 1 are executed as expected

    defer {
        schoolIsOpen = false;
    }
    
    if schoolIsOpen { //Block 1
        if(kidsInSchool.contains(child)) {
            text = "Child named \(child) is in class."
        } else {
            text = "\(child) is missing school today."
        }
        
    }
    return text;
}


print(childInSchool("george"));
print(schoolIsOpen);

 

Thank you