[swift-evolution] [Pitch] Tweak `Self` and introduce `Current`

Xiaodi Wu xiaodi.wu at gmail.com
Sat Jan 7 17:50:57 CST 2017


On Sat, Jan 7, 2017 at 5:33 PM, Braeden Profile <jhaezhyr12 at gmail.com>
wrote:

>
>> Of course, I would love being able to use an initializer setup, but there
>> are serious bugs in the implementation.
>>
>> protocol Clonable
>> {
>> 	init(other: Self)
>> }
>>
>> extension Clonable
>> {
>> 	func clone() -> Self
>> 		{ return type(of: self).init(other: self) }
>> }
>>
>>
>> class Base: Clonable
>> {
>> 	var x: Int
>> 	
>> 	init(x: Int)
>> 		{ self.x = x }
>> 	
>> 	required init(other: Base)
>> 		{ self.x = other.x }
>> }
>>
>> class Derived: Base
>> {
>> 	var y: String
>> 	
>> 	init(x: Int, y: String)
>> 	{
>> 		self.y = y
>> 		super.init(x: x)
>> 	}
>> 	
>> 	// Should be required by the Clonable protocol, but it isn't.
>> 	required init(other: Derived)
>> 	{
>> 		self.y = other.y
>> 		super.init(other: other)
>> 	}
>> 	
>> 	// Required because it was `required` in Base.  Even a `Derived` calls this initializer to clone, which is wrong.  Bugs abound.
>> 	required init(other: Base)
>> 		{ fatalError("init(other:) is wrong.") }
>> }
>>
>>
>>
>> let me = Derived(x: 1, y: "food")
>> let alienClone = me.clone() // "init(other:) is wrong."
>>
>>
> Agree. That seems wrong. Great example.
>
>
> So, is this odd behavior intentional, a bug, or a design deficiency?  I
> would think that when a protocol has a method or initializer has `Self`
> parameters—like in Clonable—every subclass would be required to implement
> its own specialized version (much like a required initializer).  That would
> be a special case of the protocol system, though.
>
> As it sits, even fixing the calling behavior of my example leaves us with
> the problem of subclasses inheriting inapplicable required initializers
> from superclasses that actually don’t make any sense.
>
> Does this deserve its own thread?
>

Dunno, maybe best to have its own thread. It's not mentioned as part of
SE-0068, but IMO a complete design that respects the spirit of that
proposal *should* involve allowing you to write:

```
class Base : Clonable {
  required init(other: Self) { ... }
}

class Derived : Base {
  required init(other: Self) { ... }
}
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170107/30ab19fd/attachment.html>


More information about the swift-evolution mailing list