Skip to content

Instantly share code, notes, and snippets.

@dagronf
dagronf / Collection+chunk.swift
Created April 30, 2024 00:43
Swift routines for chunking a collection (eg. Data, Array) into an array of chunks
extension Collection {
/// Perform a block on each chunk of `size` elements in this collection
/// - Parameters:
/// - size: The maximum size of the chunk
/// - block: The block to call with the chunk. Set `stop = true` to stop processing
func chunking(into size: Int, _ block: (SubSequence, inout Bool) -> Void) {
var stop = false
var index = 0
while index < self.count {
let offset = index + Swift.min(size, count - index)
@dagronf
dagronf / UUID+DataExtension.swift
Last active April 29, 2024 21:56
Swift UUID -> Data code extension
extension UUID {
/// Errors thrown
public enum LoadError: Error {
case invalidUUIDData
}
/// Returns the raw bytes of the UUID as a Data object.
///
/// Note that this method assumes a specific memory layout (the layout on the device calling the method)
/// and as such may not be portable to other systems.
@dagronf
dagronf / ShowSystemPreferencePanes.swift
Last active April 29, 2024 17:21
macOS: Open system preferences at a specified pane using Swift (or Objective-C) using x-apple.systempreferences
// Applescript: tell application "System Preferences" to get anchors of current pane
// Result:
// { anchor "Privacy_Reminders" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_SystemServices" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_Calendars" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Firewall" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_Assistive" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_LinkedIn" of pane id "com.apple.preference.security" of application "System Preferences",
// anchor "Privacy_Accessibility" of pane id "com.apple.preference.security" of application "System Preferences",
@dagronf
dagronf / CAAnimation+blockCallback.swift
Last active April 19, 2024 08:19
CAAnimation extension with starting/completion callback blocks
//
// CAAnimation+BlockCallback.swift
//
import UIKit
//
// Modified from http://onedayitwillmake.com/blog/2016/06/caanimation-completion-callback-block/
// Updated for Swift 4 syntax
// All credit to the original author (Mario Gonzalez)
@dagronf
dagronf / find-focus-stealer.swift
Last active April 13, 2024 12:50
Swift command-line tool to find which application is stealing your Mac's focus [macOS, script, steal, focus]
#!/usr/bin/swift
import Foundation
import AppKit.NSWorkspace
// Returns the name of the frontmost app, or <none> if no app is frontmost
func currentFocusApp() -> String {
NSWorkspace.shared.frontmostApplication?.localizedName ?? "<none>"
}
@dagronf
dagronf / Notification+Visibility.swift
Last active April 13, 2024 12:50
Observe all notifications sent through a NotificationCenter or DistributedNotificationCenter
// Observe all notifications generated by the default NotificationCenter
NotificationCenter.default.addObserver(
forName: nil, object: nil, queue: nil) { notification in
Swift.print("Notification: \(notification.name.rawValue), Object: \(notification.object)")
}
// Observe all notifications generated by the default DistributedNotificationCenter
DistributedNotificationCenter.default().addObserver(
forName: nil, object: nil, queue: nil) { notification in
Swift.print("Notification: \(notification.name.rawValue), Object: \(notification.object)")
@dagronf
dagronf / ImageConversion.swift
Last active April 13, 2024 11:00
Extensions for converting NSImage <-> CGImage <-> CIImage
extension NSImage {
/// Create a CIImage using the best representation available
///
/// - Returns: Converted image, or nil
func asCIImage() -> CIImage? {
if let cgImage = self.asCGImage() {
return CIImage(cgImage: cgImage)
}
return nil
}
@dagronf
dagronf / CGPath+squircle.swift
Last active March 8, 2024 00:37
A CGPath extension for generating squircle (superellipse) paths. Adapted from the PaintCode blog (https://www.paintcodeapp.com/news/code-for-ios-7-rounded-rectangles)
//
// Copyright © 2024 Darren Ford. All rights reserved.
//
// Adapted from the PaintCode blog: https://www.paintcodeapp.com/news/code-for-ios-7-rounded-rectangles
//
// MIT license
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
@dagronf
dagronf / synchronized.swift
Last active October 17, 2023 12:33
Swift method to provide the equivalent of `@synchronised` from objc
/// Provide the equivalent of @synchronised on objc
private func synchronized<T>(_ lock: AnyObject, _ body: () throws -> T) rethrows -> T {
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
return try body()
}
/// Simple lockable class
class Lockable {
private var lockable: AnyObject
@dagronf
dagronf / Sequence+unique.swift
Created August 23, 2023 04:12
Return the unique elements of a sequence while maintaining the order of the input sequence
public extension Sequence where Element: Equatable {
/// Return the unique elements in the array using Equatable as the predicate
var unique: [Element] {
return self.reduce(into: []) { uniqueElements, element in
if !uniqueElements.contains(element) {
uniqueElements.append(element)
}
}
}
}