Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
nicklockwood / RoundedCube.shape
Last active August 2, 2023 20:22
A reusable ShapeScript block for drawing a rounded cube
// ShapeScript document
detail 32
define roundedcube {
option radius 0.25
option size 1 1 1
detail max(4 detail)
define size_ size
define diameter radius * 2 / size_
@nicklockwood
nicklockwood / OSKit.swift
Created January 28, 2023 11:32
A lightweight approach to writing cross-platform code in SwiftUI without a lot of conditional compilation blocks
import SwiftUI
enum OSDocumentError: Error {
case unknownFileFormat
}
#if canImport(UIKit)
import UIKit
@nicklockwood
nicklockwood / Shape.swift
Created December 31, 2022 18:56
PolymorphicCoding.swift
import Foundation
// Here's a pretty typical scenario where you want to encode a polymorphic type -
// in this case a Shape type that can be either a Square or Circle. Swift provides
// a nice pattern for doing this in a type-safe way using enums:
struct Circle: Codable {
var radius: Int
}
import UIKit
extension UITextField {
/// Add a trailing placeholder label that tracks the text as it changes
func addTrailingPlaceholder(_ placeholder: String) {
let label = UILabel()
label.text = placeholder
label.alpha = 0.3
label.isHidden = true
let container = UIView()
@nicklockwood
nicklockwood / DictBench.swift
Created July 27, 2021 00:11
A quick test to compare performance of different dictionary lookups in Swift
// A quick test to compare performance of different dictionary lookups in Swift.
// Note: Results recorded on a 2020 M1 MBP. be sure to run with "Optimize for Speed [-O]
import Foundation
let iterations = 1000000
var dictionary = [Int: Int]()
for i in 0 ..< iterations {
dictionary[i] = Int.random(in: 0 ..< 1000)
@nicklockwood
nicklockwood / CodableVersioning.swift
Last active January 29, 2024 11:31
Example demonstrating how to use versioning for Codable structs
// This gist demonstrates how you can implement versioning for a Codable struct to support loading
// old serialized data after changing the structure. Notable features of this solution:
//
// * No need to make new properties optional, or to perform post-processing on the struct after
// loading in ordeer to populate missing values
// * No need to change the call site - from the outside this struct behaves just the same
// as if we had implemented codable directly in the normal way.
// * Versioning can be applied individually to parents or leaves in a larger tree of
// structs without affecting the other elements
// * This approach will work even if the original struct was not designed with versioning in mind
extension Data {
init?(hexString: String) {
let count = hexString.count / 2
var data = Data(capacity: count)
var i = hexString.startIndex
for _ in 0 ..< count {
let j = hexString.index(after: i)
if var byte = UInt8(hexString[i ... j], radix: 16) {
data.append(&byte, count: 1)
} else {
@nicklockwood
nicklockwood / Color.swift
Created January 19, 2021 23:49
Getting the Display P3 values back out of a UIColor created with init(displayP3Red:green:blue:alpha:)
import UIKit
// Create color using P3 color space
let linearColor = UIColor(displayP3Red: 1, green: 0.5, blue: 0.2, alpha: 1)
do {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
linearColor.getRed(&r, green: &g, blue: &b, alpha: &a)
print(r, g, b, a) // 1.07, 0.46, 0.0, 1.0 - not the expected values
}
@nicklockwood
nicklockwood / JaroWinkler.swift
Created December 21, 2020 18:52
Swift code to calculate the Jaro-Winkler edit distance between two strings
/// The Jaro-Winkler edit distance between two strings (0 - 1)
func editDistance(_ lhs: String, _ rhs: String) -> Double {
return 1 - jaroWinklerSimilarity(Array(lhs), Array(rhs))
}
/// Jaro-Winkler similarity between two strings (0 - 1)
/// https://www.geeksforgeeks.org/jaro-and-jaro-winkler-similarity/
private func jaroWinklerSimilarity(_ s1: [Character], _ s2: [Character]) -> Double {
var jaro = jaroSimilarity(s1, s2)
@nicklockwood
nicklockwood / main.swift
Created May 18, 2020 22:58
A simple one-file language parser and compiler test
import Foundation
enum LexingError: Error, Equatable {
case syntaxError(String)
case unexpectedEOF
}
enum ParsingError: Error {
case expected(String)
case unexpectedToken(Token)