[swift-evolution] Proposal: Protocol methods should accept default arguments
Sean Heber
sean at fifthace.com
Fri Dec 4 10:41:43 CST 2015
I ran into a situation like this in my own code and thought the same before I realized that the protocol only needs the single function that takes all of the parameters (with no need for defaults) and convenience variants can provide default values by implementing them in a protocol extension.
l8r
Sean
> On Dec 4, 2015, at 10:31 AM, Ben <ben_cocoa_dev_list at yahoo.co.uk> wrote:
>
> Hi list,
>
> I propose that methods defined in protocols should accept default arguments. This could help remove the need for method families where only one parameter is essential, but others are often used.
>
> For example:
>
> protocol Datastore {
> func executeQuery(query: String)
> func executeQuery(query: String, usingParameters: [Any])
> func executeQuery(query: String, usingParameters: [Any], logType: LogType)
> func executeQuery(query: String, usingParameters: [Any], logType: LogType, completionHandler:ClosureOfSomeSort)
> }
>
> Where typically the implementing object funnels the first three methods through to the final, more verbose method.
>
> This could be shortened to:
>
> protocol Database {
> func executeQuery(query: String, usingParameters: [Any] = [], logType: LogType = .NotLogged completionHandler:ClosureOfSomeSort? = nil)
> }
>
> Advantages:
> - Only one method to implement
> - Less to document, less cluttered interface
> - Prevent objects adopting the protocol from using different default values
> - Prevent objects from implementing similar methods in the family differently - fewer code paths to inspect, less confusion over behaviour since no argument values are hidden
>
> This fits in well with the parameters section of the Swift API design page: https://swift.org/documentation/api-design-guidelines.html#parameters
>
>
> What do you think?
>
> Regards,
>
> Ben Barnett
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list