This cheatsheet provides an overview of Swift’s unique features and includes code blocks for variables, functions, loops, conditionals, file manipulation, and more.
Declaring a variable:
var myVariable = "Hello, world!"
Declaring a constant:
let myConstant = 42
Declaring a function:
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!"
return greeting
}
Calling a function:
print(greet(person: "John"))
For loop:
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
While loop:
var i = 0
while i < 10 {
print(i)
i += 1
}
If statement:
let temperature = 70
if temperature > 65 {
print("It's warm outside!")
} else {
print("It's cold outside!")
}
Switch statement:
let planet = "Earth"
switch planet {
case "Earth":
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
Reading a file:
if let contents = try? String(contentsOfFile: "/path/to/file") {
print(contents)
}
Writing to a file:
let text = "Hello, world!"
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent("file.txt")
do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {
// Handle error
}
}