Skip to content

Instantly share code, notes, and snippets.

@ole
ole / TupleCount.swift
Last active November 22, 2024 19:57
Getting the element count of a tuple in Swift
// Overload for tuple values.
func tupleLength<each T>(_ tuple: (repeat each T)) -> Int {
var count = 0
for _ in repeat (each tuple) {
count += 1
}
return count
}
tupleLength(()) // → 0
@ole
ole / substr-mutation.swift
Created April 4, 2024 18:40
Mutating a Substring apparently makes a copy of the entire original String (in some scenarios)
// Make sure both the string and the substring are larger than 15 UTF-8 bytes
// to avoid the small string optimization
var str = "Hello world 1 Hello world 2 Hello world 3 Hello world 4 Hello world 5 Hello world 6 Hello world 7 Hello world 8 Hello world 9"
let prefixToStrip = 14
var substr = str.dropFirst(prefixToStrip).prefix(27)
let strToAppend = "+++APPENDED+++"
// ⚠️ It makes a difference how you mutate the Substring:
// - substr.append → Apparently makes a copy of the entire original string
// *and* even shifts the original string contents back to make room,
@ole
ole / swift-has-feature.sh
Last active November 21, 2024 10:32
swift-list-feature: List Swift compiler upcoming and experimental feature flags. ★ swift-has-feature: Check if a given compiler knows a specific feature flag, and whether it's an upcoming or experimental flag.
#!/bin/zsh
# Test if the Swift compiler knows about a particular language feature.
#
# Usage:
#
# swift-has-feature [--swift SWIFT_PATH] [--language-version LANGUAGE_VERSION] FEATURE
#
# The feature should be an upcoming or experimental language feature,
# such as `"StrictConcurrency"` or `"ExistentialAny"`.
@ole
ole / GroupWithTask.swift
Last active November 9, 2023 13:47
SwiftUI: Group { … }.task { … }
import SwiftUI
@main
struct GroupWithTaskApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
@ole
ole / ExtensibleFloatingPointFormatStyle.swift
Created September 9, 2023 13:33
An "extension" of FloatingPointFormatStyle that adds a `minusSign` API to customize the character(s) used as the minus sign. You could add additional extensions by following the same pattern. This demonstrates that "extending" the built-in format styles requires a lot of boilerplate because you have to replicate their APIs in your own type.
import Foundation
/// An "extension" of FloatingPointFormatStyle that adds a `minusSign` API to customize
/// the character(s) used as the minus sign.
///
/// You could add additional extensions by following the same pattern.
///
/// All other APIs are copied from FloatingPointFormatStyle and forward to it for their
/// implementation. This isn’t a full replica of the FloatingPointFormatStyle API, though,
/// because it’s only intended as a proof of concept.
@ole
ole / GenericOrdinalFormatStyle.swift
Created July 19, 2023 08:36
Generic ordinal format style for all BinaryInteger types
import Foundation
extension FormatStyle {
static func ordinal<FormatInput: BinaryInteger>() -> OrdinalFormatStyle<FormatInput>
where Self == OrdinalFormatStyle<FormatInput>
{
OrdinalFormatStyle()
}
}
@ole
ole / thirty-days-of-metal.md
Last active November 30, 2024 17:12
Warren Moore – Thirty Days of Metal
@ole
ole / NSHostingViewGenerics.swift
Created May 5, 2023 18:21
Avoiding AnyView when using NSHostingView with arbitrary content. Finding a way to specify the generic parameter.
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
FrameworkView1 {
Text("FrameworkView1")
}
.border(.red)
@ole
ole / UserDefaultsAsyncSequence.swift
Last active November 25, 2024 14:54
UserDefaults KVO observation with AsyncSequence/AsyncStream
// UserDefaults KVO observation with AsyncSequence/AsyncStream
// Ole Begemann, 2023-04
// Updated for Swift 6, 2024-11
// https://gist.github.com/ole/fc5c1f4c763d28d9ba70940512e81916
import Foundation
// This is ugly, but UserDefaults is documented to be thread-safe, so this
// should be OK.
extension UserDefaults: @retroactive @unchecked Sendable {}
@ole
ole / RelativeSizeLayout.swift
Last active October 12, 2024 09:25
A SwiftUI layout and modifier for working with relative sizes ("50 % of your container"). https://oleb.net/2023/swiftui-relative-size/
import SwiftUI
extension View {
/// Proposes a percentage of its received proposed size to `self`.
///
/// This modifier multiplies the proposed size it receives from its parent
/// with the given factors for width and height.
///
/// If the parent proposes `nil` or `.infinity` to us in any dimension,
/// we’ll forward these values to our child view unchanged.