C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: No parentheses are required around the expression being tested in an if-statement.
Tip 2: The else-if and else can be on the same line as the closing brace, or a newline. Either is accepted.
Swift program that uses if-statement, else if
var size = 10
// Test size var in if, else-if block.
if size >= 20 {
print("Big")
} else if size >= 10 {
print("Medium")
} else {
print("Small")
}
Output
Medium
And: If the condition is false, the second value is used. Here we assign an Int based on the argument to the test() func.
Swift program that uses ternary statement
func test(x: Int) {
// Use a ternary statement.
// Set y to 5 if x is 10.
// ... Set it to 0 otherwise.
let y = x == 10 ? 5 : 0
print(y)
}
// Call ternary test method.
test(x: 10)
test(x: 200)
Output
5
0
Nil: If the value exists (is not nil) the inner statements of the if are reached. We can access the constant directly.
However: If the dictionary has no data at that key (the value is nil) the inner statements of the if are not reached.
Swift program that uses if let, optional binding
let animals = ["cat": 5, "dog": 2]
// Execute inner block if constant is not nil.
if let catCount = animals["cat"] {
// This gives us a non-nil dictionary value.
print(catCount)
}
if let birdCount = animals["bird"] {
// The value is nil, so this is not reached.
print(birdCount)
} else {
print(0) // Reached.
}
Output
5
0
Here: We store the result of the even() method in constant bools. We then test those constants against true and false.
Swift program that uses bool, true, false
func even(left: Int, right: Int) -> Bool {
// Return a bool if the two arguments are equal.
return left == right
}
// Get a bool result.
let even1 = even(left: 10, right: 20)
if even1 == false {
print("Sides not even")
}
// Use bool type.
let even2: Bool = even(left: 40, right: 40)
if even2 == true {
print("Sides are even")
}
Output
Sides not even
Sides are even