Skip to content

Instantly share code, notes, and snippets.

@nhathm
Created March 20, 2017 17:52
Show Gist options
  • Save nhathm/f551c21f3c2c16946f2bdd338c3fd24f to your computer and use it in GitHub Desktop.
Save nhathm/f551c21f3c2c16946f2bdd338c3fd24f to your computer and use it in GitHub Desktop.
Example about Guard Statement
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