String Interpolation in Swift is a method for constructing new String values by embedding expressions…
Swift Operators Basics
Learn about Swift Operators. These essential symbols perform various operations on values and variables, and we’re going to explore them with easy-to-understand examples.
Assignment Operator = in Swift
The assignment operator = is used to assign a value to a variable or constant.
var score = 10
let constantScore = score
Arithmetic Operators
Addition +
Used to add two values.
let sum = 5 + 3 // sum equals 8
Subtraction –
Used to subtract one value from another.
let difference = 5 - 3 // difference equals 2
Multiplication *
Used to multiply two values.
let product = 5 * 3 // product equals 15
Division /
Used to divide one value by another.
let quotient = 6 / 3 // quotient equals 2
Compound Assignment Operators
Compound assignment operators combine assignment =Β with another operation.
Addition Assignment +=
Adds and assigns the result.
var total = 0
total += 5 // total is now 5
Subtraction Assignment -=
Subtracts and assigns the result.
var batteryLife = 100
batteryLife -= 15 // batteryLife is now 85
Multiplication Assignment *=
This operator multiplies a variable by a right-hand value and assigns the result back to the variable.
var product2 = 5
product2 *= 2 // Equivalent to product = product * 2
// product2 is now 10
Division Assignment /=
This operator divides a variable by a right-hand value and assigns the result back to the variable.
var total2 = 20
total2 /= 4 // Equivalent to total2 = total / 4
// total2 is now 5
Remainder Operator %
Used to find the remainder after division.
let remainder = 7 % 3 // remainder equals 1
Logical Operators
AND Operator &&
Returns true
if both conditions are true.
let andResult = (5 > 3) && (2 < 4) // andResult is true
OR Operator ||
Returns true
if at least one condition is true.
let orResult = (5 < 3) || (2 < 4) // orResult is true
NOT Operator !
Inverts the Boolean value.
let notResult = !(5 == 5) // notResult is false
Comparison Operators in Swift
Comparison operators in Swift are used to compare values and are crucial in making decisions in your code.
Greater than > Operator
Greater than > Operator checks if one value is greater than another.
let height1 = 180
let height2 = 175
let isTaller = height1 > height2 // isTaller is true
Less than < Operator
Less than < Operator checks if one value is less than another.
let price1 = 50
let price2 = 75
let isCheaper = price1 < price2 // isCheaper is true
Equal to == Operator
Equal to Operator == checks if two values are equal.
let score1 = 95
let score2 = 95
let isEqual = score1 == score2 // isEqual is true
Not equal to != Operator
Not equal to Operator != checks if two values are not equal.
let flavor1 = "Vanilla"
let flavor2 = "Chocolate"
let isDifferent = flavor1 != flavor2 // isDifferent is true
Greater Than or Equal To >= and Less Than or Equal To <= Operators
let speed = 55
let speedLimit = 60
let isWithinLimit = speed <= speedLimit // isWithinLimit is true
Range Operators
Swift provides several ways to represent a range of values.
Closed Range Operator … Includes both values.
for index in 1...5 {
print(index) // Prints 1 through 5
}
Half-Open Range Operator ..< Includes the lower value but not the upper value.
for index in 1..<5 {
print(index) // Prints 1 through 4
}
One-Sided Ranges: Specifying only one end of the range.
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names[2...] {
print(name) // Prints Brian and Jack
}
Ternary Conditional Operator
A shorthand for if-else statements.
let batteryLevel = 45
let batteryStatus = batteryLevel > 20 ? "Battery okay" : "Battery low"
// batteryStatus is "Battery okay"
Nil-Coalescing Operator ??
The nil-coalescing operator ?? provides a default value for an optional.
let defaultColor = "red"
var userSelectedColor: String?
let colorToUse = userSelectedColor ?? defaultColor
// colorToUse is "red" because userSelectedColor is nil
If userSelectedColor
is nil
, colorToUse
will be assigned the value of defaultColor
.
Conclusion
Operators are the fundamental building blocks in Swift programming. They enable you to perform calculations and logical operations effortlessly. Understanding and using these operators correctly will pave the way for more complex and dynamic coding.
Keep practicing these operators, and soon you’ll be handling intricate functionalities in your Swift applications with ease!