Last active
January 22, 2016 20:10
-
-
Save OscarSwanros/3a28ada2cc2a9a5666d2 to your computer and use it in GitHub Desktop.
Custom Copyable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not useful, maybe. Just a quick test.