Swift Operators and Strings
Operators calculate and compare values. Strings hold and change text.
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Add | 9 + 4 | 13 |
- | Subtract | 9 - 4 | 5 |
* | Multiply | 9 * 4 | 36 |
/ | Divide | 9 / 4 | 2 |
% | Remainder | 9 % 4 | 1 |
Dividing two Int values drops the decimal. Use Double values to keep it.
Example
print(9 / 4)
print(9.0 / 4.0)
print(9 % 4)
var wallet = 1000
wallet -= 250
wallet += 100
print(wallet)2 2.25 1 850
Swift has no ++ or -- operators. Write count += 1 instead.
Comparison and Logical Operators
Comparison operators return a Bool: == (equal), != (not equal), >, <, >= and <=.
Logical operators combine conditions:
&&means and: both sides must be true||means or: at least one side must be true!means not: flips true and false
Example
let age = 17
let hasPermission = true
print(age >= 18)
print(age >= 18 || hasPermission)
print(age >= 18 && hasPermission)
print(!hasPermission)false true false false
The Ternary Operator
condition ? valueIfTrue : valueIfFalse picks one of two values in a single line:
Example
let marks = 64
let result = marks >= 50 ? "Pass" : "Fail"
print(result)Pass
String Interpolation
Put any value or calculation inside a string with \( ):
Example
let item = "Chai"
let price = 80
print("One cup of \(item) costs Rs \(price)")
print("Three cups cost Rs \(price * 3)")One cup of Chai costs Rs 80 Three cups cost Rs 240
Working with Strings
Example
var city = "Islamabad"
print(city.count)
print(city.uppercased())
print(city.lowercased())
print(city.hasPrefix("Isla"))
print(city.hasSuffix("bad"))
print(city.contains("lama"))
print(city.isEmpty)
city += " is green"
print(city)9 ISLAMABAD islamabad true true true false Islamabad is green
| Feature | What it does |
|---|---|
count | Number of characters |
uppercased() / lowercased() | Returns the text in a new case |
hasPrefix() / hasSuffix() | Checks the start or end |
contains() | Checks if some text is inside |
isEmpty | true if the string has no characters |
+ and += | Join strings |
Multi-line Strings
Use three double quotes for text that spans several lines:
Example
let address = """
Workownix
Orangi Town
Karachi
"""
print(address)Workownix Orangi Town Karachi
Looping Through Characters
A string is a collection of characters, so a for loop can go through it:
Example
for letter in "Swift" {
print(letter, terminator: " ")
}S w i f t
Exercise
Exercise
What does print("Pakistan".count) show?
