Skip to content

Instantly share code, notes, and snippets.

@adamnemecek
Created August 3, 2016 23:31
Show Gist options
  • Save adamnemecek/2480896cec06dcfe53362d5d880f48b6 to your computer and use it in GitHub Desktop.
Save adamnemecek/2480896cec06dcfe53362d5d880f48b6 to your computer and use it in GitHub Desktop.
Copyable protocol (thanks to Mike Ash for help)
protocol Copyable: class {
init(copy: Self)
}
//
// this is a 'diffing' constructor, in your callback modify properties of $0 as needed
//
func _copy<T:Copyable, U>(obj: T, @noescape fun: inout T -> ()) -> U {
var cp = obj.dynamicType.init(copy: obj)
fun(&cp)
return cp as! U
}
extension Copyable {
func copy() -> Self {
return self.dynamicType.init(copy: self)
}
}
//
// copy struct
//
func _scopy<T>(obj: T, @noescape fun: inout T -> ()) -> T {
assert(!(obj is AnyObject))
var cp = obj
fun(&cp)
return cp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment