[swift-evolution] Proposal: Universal dynamic dispatch for method calls

Gwendal Roué gwendal.roue at gmail.com
Fri Dec 11 03:35:07 CST 2015


I wanted to thank you, Kevin Ballard, for your help, despite my stubbornness, and apologize to all readers for having diverged from the initial topic of the thread.

If you are interested, the result of this protocol clean up lies at https://github.com/groue/GRDB.swift#databasepersistable-protocol

Gwendal Roué

> Le 9 déc. 2015 à 22:13, Kevin Ballard <kevin at sb.org> a écrit :
> 
> That is nice, but if someone writes a method that's generic over <T: P> then your "override" won't get called. Seems like it's better to structure it like
>  
> protocol P {
>     func f()
> }
> extension P {
>     /// Default implementation for `f`. Calls through to `_f()`.
>     func f() { _f() }
>     /// Helper that provides the base functionality for `f`.
>     func _f() { ... }
> }
> struct S {
>     func f() {
>         ...
>         _f()
>     }
> }
>  
> This way you can write code that's generic over <T: P> (or that takes a P object directly) and it will still call the overrides.
>  
> -Kevin Ballard
>  
> On Wed, Dec 9, 2015, at 11:01 AM, Gwendal Roué wrote:
>>  
>>> Le 9 déc. 2015 à 19:52, Kevin Ballard via swift-evolution <swift-evolution at swift.org> a écrit :
>>>  
>>> b) methods defined in protocol extensions by definition can't be overridden already,
>>  
>> Methods defined in protocol extension actually can, sort of, be overridden, and this is very useful:
>>  
>>     protocol P { }
>>     extension P {
>>         func f() { … }
>>     }
>>     struct S {
>>         func f() {
>>             ...
>>             (self as P).f()
>>>>         }
>>     }
>>  
>> I know only one use case for this technique, in the groue/GRDB.swift SQLite wrapper:
>>  
>> In this library, a DatabasePersistable protocol provides basic CRUD operations, and a Record class adopts this protocol and "overrides" with the technique above the protocol methods with extra features provided by the class (especially change tracking).
>>  
>> The benefits of this architecture are:
>>  
>> - You can subclass use the full-featured Record base class, and get CRUD + change tracking for free.
>> - The Record subclasses can override the CRUD methods, and add custom code (validation, for example).
>> - You can have a custom struct adopt DatabasePersistable, and get CRUD for free.
>> - The custom structs that can also "override" the CRUD methods, and add custom code (validation, for example).
>>  
>> This is, in my opinion, a very valid use case for this "overriding".
>> Gwendal Roué
>  



More information about the swift-evolution mailing list