Skip to content

Instantly share code, notes, and snippets.

@amberstar amberstar/Copyable.swift
Last active Feb 3, 2018

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link
Owner Author

commented Nov 8, 2015

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
You can’t perform that action at this time.