Optional binding and defer statements in iOS swift

In my previous article about swift optionals, I mentioned about optional binding.

— Optional Binding (if -let statements) :

if let constantName = someOptional {
//statements using 'constantName'
} else {
// the value of someOptional is not set (or nil).

— if -var statements :

if let myValue = myObject.value as NSString? {
myValue = "Something else" // <-- Compiler error
let someOptionalString:String?someOptionalString = "abcd"if var varString = someOptionalString {print(varString) //prints abcdvarString = "efgh"print(varString) //prints efgh} else {// the value of someOptionalString is not set (or nil).}

— Guard Statement :

func greet(person: [String: String]) {guard let name = person["name"] else {return}print("Hello \(name)!")guard let location = person["location"] else {print("I hope the weather is nice near you.")return}print("I hope the weather is nice in \(location).")}greet(person: ["name": "John"])// Prints "Hello John!"// Prints "I hope the weather is nice near you."greet(person: ["name": "Jane", "location": "Cupertino"])// Prints "Hello Jane!"// Prints "I hope the weather is nice in Cupertino."
func submitForms(result:Bool) {guard result == true else {print(“result is false”)return}}
func validatePassword(password:String) ->Bool{guard password.characters.count > 3 else {print(“Password should contain atleast 3 characters”)return false}guard password.characters.count > 13 else {print(“Password should contain more than 13 characters”)return false}guard checkPasswordCharacterSet(password) else {print(“Password should contain one capital letter , one small letter, one special character”)return false}return true}

— guard - var

let a: Int? = 40func doSomething(passedA:Int?) {guard var b = passedA else {return}print (b) // prints 40b = 100print (b) // prints 100}doSomething(passedA: a)

Special case with guard statement: Optional Bool

— Defer statement :

func doSomething() {defer { print(“1”)}defer { print(“2”)}defer { print(“3”)}if 1<2 {defer { print("1<2")}}defer { print(“4”)}defer { print(“5”)}defer { print(“6”)}}

If you enjoyed reading this post, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store