💾 Archived View for gem.sdf.org › s.kaplan › cheatsheets › programming-languages › swift.md captured on 2024-08-31 at 12:51:31.
⬅️ Previous capture (2023-09-28)
-=-=-=-=-=-=-
# Swift Cheatsheet This cheatsheet provides an overview of Swift's unique features and includes code blocks for variables, functions, loops, conditionals, file manipulation, and more. ## Variables Declaring a variable:
var myVariable = "Hello, world!"
Declaring a constant:
let myConstant = 42
## Functions Declaring a function:
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!"
return greeting
}
Calling a function:
print(greet(person: "John"))
## Loops 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
}
## Conditionals 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")
}
## File Manipulation 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
}
}
## Resources - [The Swift Programming Language](https://docs.swift.org/swift-book/) - [Swift.org](https://swift.org/) - [Swift Playgrounds](https://www.apple.com/swift/playgrounds/)