Created
March 20, 2017 17:52
-
-
Save nhathm/f551c21f3c2c16946f2bdd338c3fd24f to your computer and use it in GitHub Desktop.
Example about Guard Statement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let name : String? = "Swift" | |
let nickName : String? = nil | |
// Example: Optional binding | |
// Note: underscore "_" using to ignore name of parameter when call function | |
// Example calling function below | |
func sayHiWithOptionalBinding(_ name: String?) { | |
// Using optional binding to check if object is NOT nil | |
if let checkName = name { | |
// If not nil, do some logic... | |
print("Hi \(checkName)") | |
// If logic of case object not nil too longgggggg | |
// When will you meet "else" case? | |
} else { | |
// If nil, print error or something... | |
print("Nobody Here") | |
} | |
} | |
// Example: Guard Statement | |
// Note: this is sample of not using underscore too :v | |
func sayHiWithGuard(name: String?) { | |
// Check if object is nil then do logic of nil case first | |
guard let checkName = name else { | |
// Guard statement using when we need to focus case: object is nil first | |
// Or do logic when the condition is not satisfied... | |
print("Nobody Here with Guard") | |
return | |
} | |
// If object not nil, then do logic | |
print("Hello \(checkName)") | |
} | |
// function sayHiWithOptionalBinding have underscore parameter, | |
// then do NOT need a word in front of argument | |
sayHiWithOptionalBinding(name) | |
sayHiWithOptionalBinding(nickName) | |
// function sayHiWithGuard NOT have underscore parameter, | |
// then do need a word in front of argument | |
sayHiWithGuard(name: name) | |
sayHiWithGuard(name: nickName) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment