Skip to content

Instantly share code, notes, and snippets.

@nhathm
Created March 21, 2017 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhathm/a4776b80c04bfe7b48e1aab4914480e9 to your computer and use it in GitHub Desktop.
Save nhathm/a4776b80c04bfe7b48e1aab4914480e9 to your computer and use it in GitHub Desktop.
struct Student {
let name: String?
let age: Int?
let gender: String?
}
let student = Student(name: "Rio", age: 27, gender: "Male")
func validateStudentInfo (_ student: Student) -> String {
// We do NOT need to using student name, just want to check if
// student name have value, so using underscore here
if let _ = student.name {
if let _ = student.age {
if let _ = student.gender {
return "OK"
} else {
return "Gender not valid"
}
} else {
return "Age not valid"
}
} else {
return "Name not valid"
}
}
func validateStudentInfoWithGuard (_ student: Student) -> String {
guard let _ = student.name else {
return "Name not valid"
}
guard let _ = student.age else {
return "Age not valid"
}
guard let _ = student.gender else {
return "Gender not valid"
}
return "OK"
}
validateStudentInfo(student)
validateStudentInfoWithGuard(student)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment