Skip to content

Instantly share code, notes, and snippets.

@erica
Last active May 6, 2018 01:48
Show Gist options
  • Save erica/87843a3a445f3441696b2454b1a70119 to your computer and use it in GitHub Desktop.
Save erica/87843a3a445f3441696b2454b1a70119 to your computer and use it in GitHub Desktop.
/// Returns a modified reference type
public func with<T: AnyObject>(_ this: T, update: (T) throws -> Void) rethrows -> T {
try update(this)
return this
}
/// Returns a modified copy of a value type
public func with<T>(_ item: T, update: (inout T) throws -> Void) rethrows -> T {
var this = item
try update(&this)
return this
}
// Workaround not needed with removed inout for reference types
/// Returns a modified copy of the instance
///
/// - Warning: This variation is specific for reference
/// items and includes a workaround for a Swift
/// [bug](https://bugs.swift.org/browse/SR-2773)
///
public func with<T: AnyObject>(_ item: T,
update: (inout T) throws -> Void) rethrows -> T
{
var this = item
try update(&this)
// Bug workaround. When Swift is fixed, remove this
// and remove the `AnyObject` constraint
var ptr: Unmanaged<T>? = Unmanaged<T>.passRetained(this)
.autorelease(); defer { ptr = nil }
return this
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment