Constants and Variables
- Constants are generally preferred when the value doesn't need to be changed.
- Use the
var
keyword to create and change a variable.
- Use the
let
keyword to create a constant.
- The
print()
function is useful for learning and debugging.
Example:
var name = "Ted"
name = "Rebecca"
let user = "Daphne"
print(user) // Daphne
Strings
- Swift strings are enclosed in double quotes.
- Emoji can be used in strings.
- Use a backslash to include double quotes inside a string.
- Use triple double quotes for strings that span multiple lines.
- Swift provides useful properties and methods for strings, such as
.count
, hasPrefix()
, and hasSuffix()
.
- Strings in Swift are case-sensitive.
Example:
let actor = "Tom Cruise"
let actorWithEmoji = "Tom Cruise 🏃♂️"
let quote = "He tapped a sign saying \\"Believe\\" and walked away."
let movie = """
A day in
the life of an
Apple engineer
"""
print(actor.count) // 10
print(quote.hasPrefix("He")) // true
print(quote.hasSuffix("Away.")) // true