Roberto
Roberto

Reputation: 1590

Swift distinguish several functions purposes with the same name

What is the best approach to distinguish several functions purposes with the same name in Swift. For example I have the following code:

protocol SomeProtocol {
    func simpleFunc() -> Bool
    func simpleFunc() -> Int
    func simpleFunc(type: SomeType, x: Int, y: Int) -> [SomeModel]
    func simpleFunc(type: SomeType, z: String) -> [String]
}

When I will use these functions it will be not clear what is the purpose of any of this functions. I want to do something like is done with default tableView functions. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) When I select this function I understand that it is used for didSelectRowAt

So I've done something like this:

protocol SomeProtocol {
    func simpleFunc() -> Bool /* purpose1 */
    func simpleFunc() -> Int /* purpose2 */
    func simpleFunc(purpose3 type: SomeType, x: Int, y: Int) -> [SomeModel]
    func simpleFunc(purpose4 type: SomeType, z: String) -> [String]
}

Unfortunately if function doesn't have parameters this approach will not work. What is the best practices here?

Upvotes: 0

Views: 49

Answers (1)

rmaddy
rmaddy

Reputation: 318794

The last two functions don't really have the same name from a practical point of view. In your first group of code, the last two need to be called as:

simpleFunc(type: whatever, x: 5, y: 42)
simpleFunc(type: whatever, z: "Hi")

and in your second group of code, the last two change to:

simpleFunc(purpose3: whatever, x: 5, y: 42)
simpleFunc(purpose4: whatever, z: "Hi")

Either way, the caller doesn't simply use simpleFunc. All of the parameters are involved too.

Given this, there is no reason why the first two functions can't simply be named appropriately such as:

func simpleFuncPurpose1() -> Bool
func simpleFuncPurpose2() -> Int

Then they are called, as expected:

simpleFuncPurpose1()
simpleFuncPurpose2()

All together, combined with your second group of code, the four methods are now called as follows:

simpleFuncPurpose1()
simpleFuncPurpose2()
simpleFunc(purpose3: whatever, x: 5, y: 42)
simpleFunc(purpose4: whatever, z: "Hi")

Upvotes: 1

Related Questions