Skip to content

Instantly share code, notes, and snippets.

@ole
ole / core-data-backup.swift
Last active Jun 30, 2020
How to make a copy of a Core Data SQLite database. See https://oleb.net/blog/2018/03/core-data-sqlite-backup/ for more.
View core-data-backup.swift
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
View remove-unused-namespaces.xslt
<!--
XSLT for removing unused namespaces from an XML file.
Author: Dimitre Novatchev
Source: https://stackoverflow.com/a/4594626
License: CC BY-SA, https://creativecommons.org/licenses/by-sa/2.5/
Usage:
xmlstarlet tr remove-unused-namespaces.xslt -
@ole
ole / XCTExpectation.swift
Last active Jun 2, 2020
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/
View XCTExpectation.swift
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 / UIAlertController+TextField.swift
Last active Apr 24, 2020
A UIAlertController with a text field and the ability to perform validation on the text the user has entered while the alert is on screen. The OK button is only enabled when the entered text passes validation. More info: https://oleb.net/2018/uialertcontroller-textfield/
View UIAlertController+TextField.swift
import UIKit
/// A validation rule for text input.
public enum TextValidationRule {
/// Any input is valid, including an empty string.
case noRestriction
/// The input must not be empty.
case nonEmpty
/// The enitre input must match a regular expression. A matching substring is not enough.
case regularExpression(NSRegularExpression)
@ole
ole / NotificationObserver.swift
Last active Apr 22, 2020
Demo that retaining self in a NotificationCenter observer block leads to a reference cycle you have to break manually.
View NotificationObserver.swift
// Paste into a macOS playground in Xcode and run.
// Deleting line 46 "c?.stopObserving()" triggers the assertion because
// the reference cycle caused by retaining self in the observer block is never broken.
import Foundation
let myNotification = NSNotification.Name(rawValue: "myNotification")
var cHasBeenDeallocated = false
@ole
ole / Atomic.swift
Created Jun 6, 2019
Atomic as a property wrapper
View Atomic.swift
import Dispatch
import PlaygroundSupport
@propertyDelegate
struct Atomic<A> {
private var _value: A
private let queue = DispatchQueue(label: "property wrapper")
init(initialValue: A) {
_value = initialValue
@ole
ole / units-and-locales.swift
Last active Mar 12, 2020
Paste into a playground.
View units-and-locales.swift
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 / AsyncOperation.swift
Created Aug 19, 2018
An (NS)Operation subclass for async operations
View AsyncOperation.swift
import Foundation
/// An abstract class that makes building simple asynchronous operations easy.
/// Subclasses must override `main()` to perform any work and call `finish()`
/// when they are done. All `NSOperation` work will be handled automatically.
///
/// Source/Inspiration: https://stackoverflow.com/a/48104095/116862 and https://gist.github.com/calebd/93fa347397cec5f88233
open class AsyncOperation: Operation {
public init(name: String? = nil) {
super.init()
@ole
ole / Mojave-dynamic-wallpaper-notes.md
Last active Dec 17, 2019
Reverse-engineering the dynamic wallpaper file format in macOS Mojave.
View Mojave-dynamic-wallpaper-notes.md

The dynamic wallpaper in MacOS Mojave is a single 114 MB .heic file that seems to contain 16 embedded images.

It also contains the following binary plist data in its metadata under the key "Solar". It's an array of 16 items, each with four keys:

  • i (integer). This seems to be the image index.
  • o (integer). This is always 1 or 0. Stephen Radford thinks it indicates dark mode (0) vs. light mode (1).
  • a (decimal). I’m pretty sure this is the angle of the sun over the horizon. 0º = sunset/sunrise. 90º = sun directly overhead. Negative values = sun below horizon.
  • z (decimal). This seems to be the cardinal position of the sun relative to the camera. 0º = sun is directly in front of the camera. 90º = sun is directly to the right of the camera. 180º = sun is directly behind the camera.
@ole
ole / KeyedContainer.swift
Created Dec 10, 2019
A property wrapper for dictionaries with keys that are raw-representable as strings. It modifies the wrapped dictionary's encoding/decoding behavior such that the dictionary is encoded as a dictionary (unkeyed container) rather than as an array (keyed container). For context, see https://oleb.net/blog/2017/12/dictionary-codable-array/
View KeyedContainer.swift
import Foundation
// MARK: - KeyedContainer
/// A property wrapper for dictionaries with keys that are raw-representable as strings.
/// It modifies the wrapped dictionary's encoding/decoding behavior such that the dictionary
/// is encoded as a dictionary (unkeyed container) rather than as an array (keyed container).
///
/// For context, see <https://oleb.net/blog/2017/12/dictionary-codable-array/>.
@propertyWrapper
You can’t perform that action at this time.