func validatePayment(creditCardNo:String?, expiry:String?){
if let cc = creditCardNo {
if let exp = expiry {
print("Validating credit card...")
//...
return
}
}
print("Missing Credit Card No. or Expiry Date")
}
However, the nesting of multiple if statements makes your code really unwieldy. A better way is to use the guard statement, like this:
func validatePayment(creditCardNo:String?, expiry:String?){
guard let cc = creditCardNo, let exp = expiry
else {
print("Missing Credit Card No. or Expiry Date")
return
}
//---validate credit card---
print("Validating credit card...")
}
The following shows the output of the function with the following combinations of arguments:
//---Missing Credit Card No. or Expiry Date---
validatePayment(creditCardNo: nil, expiry: "11/21")
validatePayment(creditCardNo: "1234567890123456", expiry: nil)
validatePayment(creditCardNo: nil, expiry: nil)
//---Validating credit card...---
validatePayment(creditCardNo: "1234567890123456", expiry: "11/21")
No comments:
Post a Comment