Last active
February 3, 2018 22:59
-
-
Save amberstar/0041e43fec2a94b5f47d to your computer and use it in GitHub Desktop.
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
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() |
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
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.