[swift-evolution] [Pitch] Introducing role keywords to reduce hard-to-find bugs

Douglas Gregor dgregor at apple.com
Wed Aug 23 12:08:06 CDT 2017


> On Jun 16, 2017, at 11:21 AM, Tino Heth via swift-evolution <swift-evolution at swift.org> wrote:
> 
> The described problem might be one of the most famous itches of the language, but imho the bar for new keywords* should be higher than that — and there are alternatives:
> 
> First, I guess many would like to see this to be valid Swift:
> 
> protocol Foo {
> 	func bar() {
> 		print("Default implementation called")
> 	}
> }
> 
> It's the most convenient way of avoiding typos: avoid to type ;-)

Absolutely. This is the more natural way to describe most default implementations; it’s more concise and eliminates the possibility of errors for the common case.

> Imho this might already be enough, but for a full alternative for "default", I'd suggest something like this:
> 
> extension Foo {
> 	func Foo.bar() {
> 		print("String has its own implementation")
> 	}
> }

On top of your first syntax, this would be useful when the extension is further constrained, e.g.,

extension Foo where Self: Comparable {
  func Foo.bar() {
    print(“I use Comparable for my Foo”)
  }
}


> (to make it more familiar for those with a C++ background, "Foo::bar" could be used instead ;-)

Joking aside, “Foo::bar” has one advantage if it’s applied universally: it’s unambiguous if we allow it in method references. For example, we could say

	someString.Foo::bar()

to mean “call the function that String used to satisfy the requirement Foo.bar()”. If instead it were

	someString.Foo.Foo.bar()

it looks like we’re referring to a member named “Foo” within String, and a “bar” inside that. One would end up having to write the example differently, e.g.,

	(someString as Foo).bar()

C# has set some precedent for using “.” when declaring the function, though, and there are obvious advantages to not introducing a new sigil like “::” into Swift because it brings complexity and the potential for confusion with “.”.

> 
> Additional benefit: This wouldn't be limited to protocols — and it could possibly help in weird situations when two protocols declare functions with identical signature...
> 
> extension String: Foo {
> 	func Foo.bar() {
> 		print("String has its own implementation")
> 	}
> 
> 	func Foo.barr() {
> 		// compiler error, Foo defines no function "barr"
> 	}
> 
> 	func barr() {
> 		// this is fine, no connection to a protocol
> 	}
> }

Absolutely.

Thanks for writing this up, Tino; I was going to send a very similar response :)

	- Doug

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170823/aec51d1a/attachment.html>


More information about the swift-evolution mailing list