Skip to content

Instantly share code, notes, and snippets.

@IanKeen
IanKeen / NotificationCenter+TypeSafe.swift
Last active December 7, 2022 21:31
Type safe NotificationCenter
struct Notification<T> {
let name: NSNotification.Name
}
private let notificationData = "_notificationData"
extension NotificationCenter {
func post<T>(_ notification: Notification<T>, object: Any? = nil, data: T) {
post(name: notification.name, object: object, userInfo: [notificationData: data])
}
@IanKeen
IanKeen / Example+Object.swift
Last active August 2, 2023 16:39
Simple, highly composable Validator
extension Validator where Input == User, Output == User {
static var validUser: Validator<User, User> {
return .keyPath(\.name, .isNotNil && .isNotEmpty)
}
}
struct User {
let name: String?
}
@ole
ole / AsyncOperation.swift
Created August 19, 2018 16:47
An (NS)Operation subclass for async operations
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 / UIAlertController+TextField.swift
Last active January 24, 2025 19:07
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/
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)
@IanKeen
IanKeen / Decodable+Random.swift
Last active March 29, 2022 13:06
Custom Decoder that can be used to create Decodable instances that are populated with random values
import Foundation
extension Decodable {
public static func randomInstance() throws -> Self {
let decoder = RandomDecoder()
return try Self(from: decoder)
}
}
private class RandomDecoder: Decoder {
@calda
calda / SortDescriptor.swift
Created July 20, 2018 00:45
SortDescriptor.playground
import Foundation
// MARK: SortDescriptor
/// Type-erased Sort Descriptor (can store multiple in the same array
/// regardless of the underlying KeyPath
public struct SortDescriptor<Element> {
private let comparator: (Any, Any) -> Bool
@IanKeen
IanKeen / Dictionary+Map.swift
Created July 7, 2018 20:09
Map from `Dictionary<Key, Value>` to `Dictionary<T, U>`
public extension Dictionary {
public func mapPairs<T: Hashable, U>(_ transform: ((key: Key, value: Value)) throws -> (key: T, value: U)) rethrows -> [T: U] {
return .init(uniqueKeysWithValues: try self.map(transform))
}
}
let x = ["1": 1, "2": 2, "3": 3]
let y = x.mapPairs { (Int($0.key)!, "\($0.value)") }
print(x) // ["1": 1, "2": 2, "3": 3]
import UIKit
class PassThroughView: UIView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let result = super.hitTest(point, with: event)
if result == self { return nil }
return result
}
@IanKeen
IanKeen / Partial.swift
Last active September 10, 2024 11:59
Partial<T>
/// A wrapper for a partial representation of a `T`.
/// It can be constructed over time, then later used to
/// build a complete `T`
@dynamicMemberLookup
public struct Partial<T> {
enum Error: Swift.Error {
case invalid(PartialKeyPath<T>)
}
// MARK: - Private Properties
@khanlou
khanlou / Data+PushNotifications.swift
Created March 10, 2018 16:00
How to generate a hex string for push notifications
import Foundation
extension Data {
var hexString: String {
return self.map({ return String(format: "%02hhx", $0) }).joined()
}
}