Skip to content

Instantly share code, notes, and snippets.

@ole
ole / core-data-backup.swift
Last active January 1, 2024 16:52
How to make a copy of a Core Data SQLite database. See https://oleb.net/blog/2018/03/core-data-sqlite-backup/ for more.
import CoreData
import Foundation
/// Safely copies the specified `NSPersistentStore` to a temporary file.
/// Useful for backups.
///
/// - Parameter index: The index of the persistent store in the coordinator's
/// `persistentStores` array. Passing an index that doesn't exist will trap.
///
/// - Returns: The URL of the backup file, wrapped in a TemporaryFile instance
@ole
ole / units-and-locales.swift
Last active March 12, 2020 04:01
Paste into a playground.
import Foundation
// Playing around with MeasurementFormatter.string(from: Unit)
let f = MeasurementFormatter()
f.locale = Locale(identifier: "de_DE")
f.unitOptions = .naturalScale
f.unitStyle = .long
f.string(from: UnitSpeed.milesPerHour)
f.string(from: UnitTemperature.celsius)
@ole
ole / XCTExpectation.swift
Last active December 6, 2021 13:10
A variant of XCTKVOExpectation that works with native Swift key paths. To try it out, paste the code into an Xcode playground and observe the unit test output in the console. See my blog post at https://oleb.net/blog/2018/02/xctkvoexpectation-swift-keypaths/
import XCTest
/// An expectation that is fulfilled when a Key Value Observing (KVO) condition
/// is met. It's variant of `XCTKVOExpectation` with support for native Swift
/// key paths.
final class KVOExpectation: XCTestExpectation {
private var kvoToken: NSKeyValueObservation?
/// Creates an expectation that is fulfilled when a KVO change causes the
/// specified key path of the observed object to have an expected value.
@ole
ole / URLSession.swift
Created February 22, 2018 00:08
Paste this into a playground and let it run for 5 seconds. You’ll get a non-nil response *and* error.
import Foundation
import PlaygroundSupport
let bigFile = URL(string: "https://speed.hetzner.de/1GB.bin")!
let task = URLSession.shared.dataTask(with: bigFile) { (data, response, error) in
print("data: \(data)")
print("response: \(response)")
print("error: \(error)")
}
task.resume()
let s = "Hello World"
let evenIndices = s.indices.enumerated()
.filter { $0.offset % 2 == 0 }
.map { $0.element }
for idx in evenIndices {
print(s[idx])
}
Process: Notes [17745]
Path: /Applications/Notes.app/Contents/MacOS/Notes
Identifier: com.apple.Notes
Version: 4.5 (863)
Build Info: Notes-863000000000000~1
Code Type: X86-64 (Native)
Parent Process: ??? [1]
Responsible: Notes [17745]
User ID: 501
@ole
ole / type-pattern-matching.swift
Last active October 12, 2017 16:51
Pattern matching for types. See https://twitter.com/Gernot/status/918490645118976000 for context.
func ~= <T, U> (pattern: T.Type, value: U.Type) -> Bool {
return pattern == value
}
func f<T>(_ type: T.Type) {
switch T.self {
case Int.self:
print("Int")
default:
print("Something else")
let str = "👨🏾‍🚒"
print(str.unicodeScalars.map { "0x\(String($0.value, radix: 16))" })
// → ["0x1f468", "0x1f3fe", "0x200d", "0x1f692"]
print(str.utf16.map { "0x\(String($0, radix: 16))" })
// → ["0xd83d", "0xdc68", "0xd83c", "0xdffe", "0x200d", "0xd83d", "0xde92"]
print(str.utf16.count)
// → 7
let utf16Offset = 2
@ole
ole / fun-with-string-interpolation.swift
Last active June 13, 2018 15:02
Fun with String Interpolation — For more information read my article at https://oleb.net/blog/2017/01/fun-with-string-interpolation/. — Dependencies: Foundation
/// An unescaped string from a potentially unsafe
/// source (such as user input)
struct UnsafeString {
var value: String
}
/// A string that either comes from a safe source
/// (e.g. a string literal in the source code)
/// or has been escaped.
struct SanitizedHTML {
@ole
ole / MeasurementParsing.swift
Last active January 27, 2017 18:04
Parse measurement expressions like `"5 m²"` and convert them into `Measurement` values. Uses the Objective-C runtime to find the known and valid symbols for a given unit (such as `UnitArea`). Adopts `ExpressibleByStringLiteral` for easy initialization.
// Parse measurement expressions like `"5 m²"` and convert them into `Measurement` values.
// Uses the Objective-C runtime to find the known and valid symbols for a given unit
// (such as `UnitArea`). Adopts `ExpressibleByStringLiteral` for easy initialization.
import ObjectiveC
enum ObjectiveCRuntime {
class Class {
let base: AnyClass