Hi, all
I'd like to start a new SE proposal regarding private function parameters, and I have searched the site and no similar proposals/posts are present. The detail is as follows:
I'd like to propose the support for private function parameters, which is a parameter non-visible to the outside of the class/struct/whatever. The useful cases includes, but is not limited to, when you want to preserve states between recursive calls and do not want to create an instance variable for that. Example would be when a loadData
function needs to retry once and only once when it fails, so it uses a parameter retryIfFailed
to determine whether it should retry.
class DataManager {
// parameter retryIfNeeded is private
func loadData(id: String, retryIfNeeded: Bool = true, completion: @escaping (Data) -> Void) {
// load data...
if (failed) {
if (retryIfNeeded) {
loadData(id: id, retryIfNeeded: false, completion: completion)
} else {
// report failure
}
}
}
}
In the case above, retryIfNeeded
should both have a default value and be inaccessible from outside of DataManager
, as there should be no way to configure it.
Proposed new function signature:
func loadData(id: String, retryIfNeeded: private Bool = true, completion: @escaping (Data) -> Void)
One could argue that this can be achieved via making this method entirely private and creating a public method without the parameter. This is true, and is exactly what I intend to have the compiler do for me, should Swift supports this feature. Specifically, the compiler already has similar mechanisms regarding default parameters. When the compiler finds functions with default parameters, it automatically generates "specialized" versions of the same function and calls one of those at callsites if parameters are left out. If the compiler can do the same — generate specialized versions of methods with private parameters left out and calls those at callsites outside of the class — it would save us programmers lots of time, just like how default parameters has already save us lots of time.
Given the context, supporting private parameters should not be hard to implement, and any argument that goes against it because it's just like a "syntactical sugar," would mostly likely also go against default parameters since it's also just kind of a "syntactical sugar" that's automatically converted into multiple specialized functions by the compiler.
Please share your opinion on this!
Thanks,
Nick