Skip to content

Instantly share code, notes, and snippets.

@frboulais
Last active October 20, 2022 18:01
Show Gist options
  • Save frboulais/43720e8c77ee22a2b4a2072e7fed385a to your computer and use it in GitHub Desktop.
Save frboulais/43720e8c77ee22a2b4a2072e7fed385a to your computer and use it in GitHub Desktop.
Cheat sheet for Swift formatters (iOS 15+)
//
// FormatterCheatSheet.swift
//
// Created by François Boulais on 20/10/2022.
// Copyright © 2022 App Craft Studio. All rights reserved.
//
import Contacts
import Foundation
let now: Date = .now
print(now.formatted(.dateTime.year().month()))
// "Oct 2022"
let tomorrow: Date = now + 24 * 3_600
print((now..<tomorrow).formatted(.components(style: .wide)))
// "1 day"
let yesterday = now - 24 * 3_600
print(yesterday.formatted(.relative(presentation: .named)))
// "yesterday"
let price: Double = 29.99
print(price.formatted(.currency(code: "USD")))
// "29.99"
let percent: Double = 0.78
print(percent.formatted(.percent))
// "78%"
let area = Measurement<UnitArea>(value: 150, unit: .squareFeet)
print(area.formatted(.measurement(width: .narrow)))
// "150ft²"
let size: Int = 256_000
print(size.formatted(.byteCount(style: .binary)))
// "250kB"
let daltons = ["Joe", "William", "Jack", "Averell"]
print(daltons.formatted(.list(type: .and)))
// "Joe, William, Jack, and Averell"
var components = PersonNameComponents()
components.givenName = "Steve"
components.familyName = "Jobs"
print(components.formatted(.name(style: .abbreviated)))
// "SJ"
let address = CNMutablePostalAddress()
let addressFormatter = CNPostalAddressFormatter()
address.street = "128 rue La Boétie"
address.postalCode = "75008"
address.city = "Paris"
address.country = "France"
print(addressFormatter.string(from: address))
// 128 rue La Boétie
// Paris 75008
// France
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment