Swift Tutorial menu

Swift Operators and Strings

Operators calculate and compare values. Strings hold and change text.

Arithmetic Operators

OperatorNameExampleResult
+Add9 + 413
-Subtract9 - 45
*Multiply9 * 436
/Divide9 / 42
%Remainder9 % 41

Dividing two Int values drops the decimal. Use Double values to keep it.

Example

swift
print(9 / 4)
print(9.0 / 4.0)
print(9 % 4)

var wallet = 1000
wallet -= 250
wallet += 100
print(wallet)
Output
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

swift
let age = 17
let hasPermission = true
print(age >= 18)
print(age >= 18 || hasPermission)
print(age >= 18 && hasPermission)
print(!hasPermission)
Output
false
true
false
false

The Ternary Operator

condition ? valueIfTrue : valueIfFalse picks one of two values in a single line:

Example

swift
let marks = 64
let result = marks >= 50 ? "Pass" : "Fail"
print(result)
Output
Pass

String Interpolation

Put any value or calculation inside a string with \( ):

Example

swift
let item = "Chai"
let price = 80
print("One cup of \(item) costs Rs \(price)")
print("Three cups cost Rs \(price * 3)")
Output
One cup of Chai costs Rs 80
Three cups cost Rs 240

Working with Strings

Example

swift
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)
Output
9
ISLAMABAD
islamabad
true
true
true
false
Islamabad is green
FeatureWhat it does
countNumber 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
isEmptytrue if the string has no characters
+ and +=Join strings

Multi-line Strings

Use three double quotes for text that spans several lines:

Example

swift
let address = """
Workownix
Orangi Town
Karachi
"""
print(address)
Output
Workownix
Orangi Town
Karachi

Looping Through Characters

A string is a collection of characters, so a for loop can go through it:

Example

swift
for letter in "Swift" {
    print(letter, terminator: " ")
}
Output
S w i f t 

Exercise

Exercise

What does print("Pakistan".count) show?

Learn Swift with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp