Documents, reminders and "cheat sheets" I use in everyday development
let actor = "Denzel Washington"
let filename = "paris.jpg"
let result = "⭐️ You win! ⭐️"
let quote = "Then he tapped a sign saying \"Believe\" and walked away."
let movie = """
A day in
the life of an
Apple engineer
""" // whitespace ahead of lines trimmed to here
actor.count // 17
result.uppercased() // "⭐️ YOU WIN! ⭐️"
movie.hasPrefix("a day") // false -- case matters!
filename.hasSuffix(".jpg") // true
string.components(separatedBy: "\n")
string.trimmingCharacters(in: .whitespacesAndNewlines)
var presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe", "Adams"]
map(_:) // from Sequence
flatMap(_:) // append elements of returned sequences individually
compactMap() // non-nil returned elements only
reduce(_:_:) // closure returns a new result object
reduce(into:_:) // closure mutates inout result object
lazy:
| Mutating | Non-Mutating |
|---|---|
sort(by:) |
sorted(by:) |
reverse() |
reversed() |
shuffle(using:) |
shuffled(using:) |
partition(by:) |
|
swapAt(,) |
split(separator:maxSplits:omittingEmptySubsequences:)
split(maxSplits:omittingEmptySubsequences:whereSeparator) // closure
joined(separator:)
difference(from:by:)
applying()
print(presidents.count)
print(presidents.sorted())
presidents.remove(at: 5)
print(presidents)
print(presidents.contains("Washington"))
print(presidents.contains("Hubbard"))
print(presidents.reversed())
presidents.sort()
presidents.reverse()
presidents.randomElement() ?? "Empty string"
presidents.removeFirst()
presidents.removeLast()
presidents.popLast() -> Element?
var a = Array(repeating: Array(repeating: 0, count: 8), count: 8)
let employee2 = [
"name": "Taylor Swift",
"job": "Singer",
"location": "Nashville" ]
print(employee2["name"]) // Optional("Taylor Swift")
print(employee2["job"] ?? "Unknown")
print(employee2["location"])
print(employee2["password"]) // nil
print(employee2["favorite color"] ?? "Unknown") // Unknown
print(employee2["favorite color", default: "red"]) // red
let names = [true: "true", false: "false"]
print(names[true])
print(employee2["favorite ice cream flavor", default: "Vanilla"])
func getUser() -> (firstName: String, lastName: String) {
("Taylor", "Swift")
}
{ up to the keyword in.() means the same thing as Void$0…$n omit parameter listvar computedProperty: Type {
/* compute value */
}
var computedProperty: Type {
get {
/* compute value */
}
set {
/* mutate stuff */
}
}
var propertyObservers: Type {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
open /* allow subclassing */publicpackage /* multi-module package */internal /* current module -- default */fileprivateprivateself – current value of a structSelf – current type of a structenum so it can’t be instantiatedstatic variable private so only the struct’s static methods can access it.some Foo – some specific class that implements Foo. The compiler figures it out.any Foo ???struct User: Equatable { // Swift automatically writes piecewise equality test
let name: String
}
extension Numeric {
func squared() -> Self {
self * self
}
}
let theyMightBeGiants: [Giant?]
let wereCertainlyDwarfs: [Dwarf]
optional ?? valueIfNil
let author2 = book2?.author?.first?.uppercased() ?? "A"
guard let at top of functionlet user = (try? getUser(id: 23)) ?? "Error"
try! if you promise the called function will never throwfunc identity<A>(_ value: A) -> A {
return value
}
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
let log = Logger(subsystem: "com.josh.example", category: "error")
struct MyValueType: Codable, Sendable, Identifiable, Hashable {}
DateComponents
MyClass: Codable { }
enum CodingKeys: String, CodingKey { }
if let encoded = try? JSONEncoder().encode(object) { }
if let decodedObject = try? JSONDecoder().decode(DecodedObjectType.self, from: encoded) { }
let (data, _) = try await URLSession.shared.data(from: url)
let recentChangesResponse = try JSONDecoder().decode(RecentChangesResponse.self, from: data)
recentChanges = recentChangesResponse.query.recentchanges
async functions run on the global (background) executorasync functions run on the caller’s actor@concurrent functions run on global executor whether async or not@MainActor for new projects)
nonisolated(nonsending) — nonisolated functions run on caller’s actor whether async or not@Model class ModelClass {
WindowGroup {
ContentView()
}
.modelContainer(for: ModelClass.self)
#Preview {
do {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(for: User.self, configurations: config)
let user = User(name: "Taylor Swift", city: "Nashville", joinDate: .now)
return EditUserView(user: user)
.modelContainer(container)
} catch {
return Text("Failed to create container: \(error.localizedDescription)")
}
}
import CoreImage.CIFilterBuiltins