[swift-users] Question with calling a method which returns `Self` on super
吴君恺
wjk_buaa at 163.com
Thu Aug 10 22:15:58 CDT 2017
Hi all,
here is the scenario, I want to implement a Copying protocol which can be used homogeneously
protocol Copying {
func copy() -> Self
}
Because this protocol contains neither associated-type-requirements or self-requirements(requiring a method returning Self is different), it can surely be used homogeneously.
let objects: [Copying] = ....
for copyable in objects {
.....
}
It will work if I make one of my base class conform to Copying
class Shape: Copying {
var color: UIColor?
required init() {}
func copy() -> Self {
let copied = type(of: self).init()
copied.color = color
return copied
}
}
The implementation of `copy` above is forced by compiler to avoid any explicit specification of type `Shape`, so that the returning value will have a dynamic type, which is just what I want. Here, the type of `copied` is `Self`
However, if I try to make a subclass of Shape, I can't find a elegant way to implement this `copy` method in that subclass, the following code will not compile.
class Circle: Shape {
var radius: Float = 5
func copy() -> Self {
let copied = super.copy()
copied.radius = radius // compilation error
return copied
}
}
The compiler will complain that `copied` has no property `radius`. It turns out that calling copy() on super will yield a value of type Shape, rather than Self.
Swift now forbids explicit conversion to `Self` (I totally agree with this rule), and will automatically allow `Self` to be treated as a specific type in some circumstances. But for this case, I wonder whether this is the correct behavior or a bug? Why calling `super.copy()` not be able to get a `Self`?
I did find a work-around for this problem afterwards, but this question really haunts me...
Cheers,
Lincoln.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170811/485ff197/attachment.html>
More information about the swift-users
mailing list