Skip to content

Instantly share code, notes, and snippets.

@JettIsOnTheNet
Created June 17, 2024 15:31
Show Gist options
  • Save JettIsOnTheNet/81b8c93547a0a8d2ef466b22c8d7ea5e to your computer and use it in GitHub Desktop.
Save JettIsOnTheNet/81b8c93547a0a8d2ef466b22c8d7ea5e to your computer and use it in GitHub Desktop.
Syntax example scan sheet for Swift.
// Swift up to speed
import Foundation
// variables and constants
var integerVar: Int = 10
let stringVar: String = "Hello, Swift!"
// functions
func greet(name: String) -> String {
return "Hello \(name)!"
}
// for-in loop
for i in 1...5 {
print("For loop iteration: \(i)")
}
// while loop
var count = 5
while count > 0 {
print("While loop iteration: \(count)")
count -= 1
}
// conditional statements
if integerVar > 5 {
print("Integer is greater than 5")
} else if integerVar == 5 {
print("Integer is 5")
} else {
print("Integer is less than 5")
}
// data structures
var numbers: [Int] = [1, 2, 3, 4, 5]
var dictionary: [String: Int] = ["a": 1, "b": 2]
// optionals
var optionalString: String? = "This is optional"
if let safeString = optionalString {
print("Unwrapped optional: \(safeString)")
} else {
print("Optional was nil")
}
// error handling
enum FileError: Error {
case fileNotFound, unreadable, encodingFailed
}
func readFile(path: String) throws -> String {
guard let data = FileManager.default.contents(atPath: path) else {
throw FileError.fileNotFound
}
guard let content = String(data: data, encoding: .utf8) else {
throw FileError.encodingFailed
}
return content
}
// file I/O
let filePath = "example.txt"
do {
let content = try readFile(path: filePath)
print("File content: \(content)")
} catch {
print("An error occurred: \(error)")
}
// concurrency
DispatchQueue.global().async {
print("This is running on a background thread")
DispatchQueue.main.async {
print("Back on the main thread")
}
}
// main
print(greet(name: "World"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment