Overloading nested functions in Swift

The overloading methods in Swift work as expected, but when I try to overload nested functions like

func foo() {
    func bar(param: Int) {
        // do stuff
    }
    func bar(param: Double) {
        // do stuff
    }

    // call functions here
}

      

I am getting an error Definition conflicts with previous value

. Why is this happening?

+3


source to share


2 answers


IMHO, this is understandable if you are considering this option:

func foo() {

    let bar: (param: Int) -> () = { p in
        // do stuff
    }

    func bar(param: Double) {
        // do stuff
    }

    // call functions here
}

      

With your first function definition, bar

you simply declare a type constant (param: Int) -> ()

. So with your second declaration, you are declaring another constant of a different type (param: Double) -> ()

, but with the same name as the one already declared bar

.

In short, as you wrote:



let bar: Int = 0
let bar: Double = 0.0

      

In this case, the compiler will also complain.

Hope it helps.

+3


source


Good question.

Note that this behavior / limitation is not documented and the answer is my best guess.

Consider the following piece of code:

func foo() -> (param:Int)->() {
    func bar(param: Int) {
        // do stuff
    }
    return bar
}

      

The function will return a closure bar

. If you had another named closure bar

inside the same function like this ...

func foo() -> (param:Int)->() {
    func bar(param: Int) {
        // do stuff
    }
    func bar(param: Float) {
        // do stuff
    }
    return bar
}

      

... they will have conflicting names and the compiler will not know what to return. This is the same as the following piece of code, which you can easily agree to be wrong:

func foo() -> Int {
    let a:Int = 0
    let a:Int = 0 //Error
    return a
}

      



More observations

The behavior of such a set of functions inside a class is strange.

class Test {
    func foo(param:Float) {
        let bar = { (param:Int) -> () in
            //do stuff
        }
    }
    func foo(param:Int) {
        let bar = { (param:Int) -> () in
            //do stuff
        }
    }
    func anotherFoo() {
        println(self.foo) //Compile time error - Ambiguous use of foo
    }
}

      

Everything though ...

class Test {
    func foo(param:Float) {
        let bar = { (param:Int) -> () in
            //do stuff
        }
    }
    func anotherFoo() {
        println(self.foo) //Compiles
    }
}

      

Interesting.

+1


source







All Articles