Skip to content

Instantly share code, notes, and snippets.

@amberstar
Last active February 3, 2018 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amberstar/0041e43fec2a94b5f47d to your computer and use it in GitHub Desktop.
Save amberstar/0041e43fec2a94b5f47d to your computer and use it in GitHub Desktop.
Copyable
protocol Copyable {
typealias CopyType
func copy() -> CopyType
}
class A: Copyable {
var x: Int
init(x: Int) { self.x = x }
func copy() -> A {
return A(x: self.x)
}
}
class B: A {
var y : Int
init(x: Int, y: Int) {
self.y = y
super.init(x: x)
}
override func copy() -> B {
return B(x: self.x, y: self.y)
}
}
let a = A(x: 1)
let b = a.copy()
let c = B(x: 1, y: 2)
let d = c.copy()
@rnapier
Copy link

rnapier commented Nov 8, 2015

Trouble is that CopyType can be anything. So to use Copyable in a useful way, we have to put it in a generic with a constraint of "C: Copyable where C.CopyType == C". Since it has an associated type, you can't accept a parameter of type "Copyable."

Your current code would work just as well if Copyable didn't exist; it's really just methods that happen to be on the classes. I suspect in practice this will make it not worth the trouble. Still, the closest to useful I've seen so far.

Of course I've been spending a lot of time thinking about what I'd use Copyable for. I keep feeling like I need it, but I don't think it's ever shown up in pure Swift code, and when bridging to ObjC I have to use NSCopying in practice anyway.

@amberstar
Copy link
Author

For sure. It's not useful in practice. A type requirement of Self in a protocol should travel down the class inheritance chain. I don't think it makes any practical sense the way it behaves now.

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