Foundation Essentials

Foundation is available on all Swift platforms (the open-source swift-foundation rewrite unifies behavior on Apple platforms, Linux, and Windows).

40.1 Dates, Durations and Formatting

let now = Date()
let calendar = Calendar.current
let tomorrow = calendar.date(byAdding: .day, value: 1, to: now)!
let components = calendar.dateComponents([.year, .month, .day, .weekday], from: now)
let birthday = calendar.date(from: DateComponents(year: 1995, month: 6, day: 15))!
let age = calendar.dateComponents([.year], from: birthday, to: now).year!

now.formatted(date: .abbreviated, time: .shortened)            // "Oct 24, 2025 at 10:30 AM"
now.formatted(.iso8601)
now.formatted(.dateTime.year().month(.wide).day())
let parsed = try Date("2025-10-24T10:00:00Z", strategy: .iso8601)
now.addingTimeInterval(3600)
now.timeIntervalSince(birthday)

let duration = Duration.seconds(90)
duration.formatted(.units(allowed: [.minutes, .seconds]))       // "1 min, 30 sec"
let clock = ContinuousClock()
let elapsed = clock.measure { heavyWork() }

40.2 Number, Measurement and List Formatting

1234.5.formatted(.currency(code: "INR"))                  // "₹1,234.50"
0.256.formatted(.percent)                                 // "25.6%"
1_500_000.formatted(.number.notation(.compactName))       // "1.5M"
Measurement(value: 5, unit: UnitLength.kilometers).converted(to: .miles).formatted()
["Ana", "Bo", "Cy"].formatted(.list(type: .and))          // "Ana, Bo, and Cy"
PersonNameComponents(givenName: "Ana", familyName: "Rao").formatted()
ByteCountFormatStyle().format(1_048_576)                  // "1 MB"

40.3 URLs and Files

var components = URLComponents(string: "https://api.example.com/search")!
components.queryItems = [URLQueryItem(name: "q", value: "swift concurrency"), URLQueryItem(name: "page", value: "1")]
let url = components.url!
let docs = URL.documentsDirectory
let file = docs.appending(path: "notes.txt")

try "Hello".write(to: file, atomically: true, encoding: .utf8)
let text = try String(contentsOf: file, encoding: .utf8)
let fm = FileManager.default
fm.fileExists(atPath: file.path())
try fm.createDirectory(at: docs.appending(path: "Exports"), withIntermediateDirectories: true)
let contents = try fm.contentsOfDirectory(at: docs, includingPropertiesForKeys: [.fileSizeKey])
try fm.removeItem(at: file)
let data = try Data(contentsOf: file)

40.4 Other Foundation Types

UUID, Data (bytes, base64: data.base64EncodedString()), Locale, TimeZone, NotificationCenter, UserDefaults, ProcessInfo (environment variables, processorCount), Bundle (resources), NSPredicate vs #Predicate, AttributedString (rich text with Markdown: try AttributedString(markdown: "bold")), Scanner, CharacterSet, and Decimal (money).