Skip to content

Instantly share code, notes, and snippets.

@anandabits
anandabits / ClosedProtocol.swift
Created February 11, 2018 21:30
Emulating closed protocols in Swift
// This example shows how closed protocols can be emulated in Swift today.
// The technique leverages Swift's support for public (but not open) classes.
// First, it's worth observing that there is an almost trivial technique that can be used when
// it is possible to specify a (possibly abstract) superclass for all conforiming types.
// Simply declare a public (not open) base class and a protocol with a Self inheritance constraint.
// Swift does not support open subclasses of a public superclass so no classes outside the module
// will be able to meet the self inheritance constraint.
public class FooBase {}
public protocol Foo where Self: FooBase {}
@dabrahams
dabrahams / CowBuffer.swift
Created March 31, 2017 03:37
A way to ask about uniqueness of class references, without a struct wrapper
extension ObjectIdentifier {
/// Returns true if the object identified by `self` is uniquely referenced.
///
/// - Requires: the object identified by `self` exists.
/// - Note: will only work when called from a mutating method
internal func _liveObjectIsUniquelyReferenced() -> Bool {
var me = self
return withUnsafeMutablePointer(to: &me) {
$0.withMemoryRebound(to: AnyObject.self, capacity: 1) {
_isUnique(&$0.pointee)