Skip to content

Instantly share code, notes, and snippets.

@OscarSwanros
Last active January 22, 2016 20:10
Show Gist options
  • Save OscarSwanros/3a28ada2cc2a9a5666d2 to your computer and use it in GitHub Desktop.
Save OscarSwanros/3a28ada2cc2a9a5666d2 to your computer and use it in GitHub Desktop.
Custom Copyable
import Foundation
protocol Copyable {
typealias C
init()
func _copy() -> C
}
class CopyBox<T: Copyable> {
let internalCopyable: T
init(copyable: T) {
internalCopyable = copyable
}
func generateCopy() -> T? {
let c = internalCopyable._copy() as? T
return c
}
}
class A: Copyable {
var s: String
var customString: String {
return "Custom String"
}
required init() {
s = ""
}
init(s: String) {
self.s = s
}
func _copy() -> A {
return A(s: s + " Copied")
}
}
class X: A {
override var customString: String {
return "Modified Custom String"
}
override func _copy() -> A {
return X(s: s)
}
}
class B<P: A where P: Copyable> {
let aInstance: P
init(a: P) {
aInstance = a
}
func test() {
let box = CopyBox<P>(copyable: aInstance)
if let copy = box.generateCopy() {
print(copy.s)
print(copy === aInstance)
}
else {
print("nil")
}
}
}
let x = X(s: "My String")
x.customString
let b = B<X>(a: x)
b.test()
// #=> "My String Copied"
// #=> false
@OscarSwanros
Copy link
Author

This is not useful, maybe. Just a quick test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment