Conditionals
Overview
Conditionals should cover all the possibilities, else the output will be an error.
if
let a = true
let b = true
if a && b {
print("Hello, Swift!")
}
// compile: true
// Both a and b are trueif not: ”if !”
Guard
guard => Guard this rule
else => if result not as we needed then do this
return => finish the process
throw => ???
Sources
if vs Guard
Do-catch, Do-try
Sources
Switch
the difference between if-else
If-else allows duplicate criteria whereas switch does not. This is the main difference between them
default:
In some cases, you will have dozens if not hundreds of criteria, in those cases normally you will need to describe all of them in switch formula. But swift does not require it, and with the help of "default:" case, it allows you to describe a result for all other cases at once.
The "default:" criteria must be at the end, otherwise swift will throw an error message, "Additional 'case' blocks cannot appear after the 'default' block of a 'switch'"
fallthrough
In some cases, you may need to merge multiple cases in order.
"fallthrough" Allows you to merge multiple (ordered) criteria. You can use it as many times as you want.
Ternary Conditional Operator
Criteria ? :
"criteria": > || < || = || ! || !=
"?": True
":" False
This squence also called as WTF
W: What to check
T: if True
F: if False
You cannot insert an "if-else" statement in a "print", you can only insert "print" in an "if-else".
The other solution which is more readable is to use a ternary in a "print". #control
Ternary conditions also shorten your code.
Sources
Videos
Articles / Documents
Last updated
Was this helpful?