Nested Function in Swift return type casting error

advertisements

Original Code:

func makeIncrement()->(Int->Int){
    func addOne(Number:Int)->Int{
        return 1 + Number
    }

    return addOne
}

Question One: does the (Int->Int) interrupted like this -- first Int is the return type of inner function, second Int is return type of the outer? I did little experiment myself by changing code to:

func makeIncrement()->(Int->String){
    func addOne(Number:Int)->Int{
        return 1 + Number
    }

    return String(addOne)
}

error pop up says NSString is not a subtype of Int->String

I tried other way around (reverse return type, but gave me similar errors)

Question Two: How does this type of casting work in this case ?


addOne is a function. You cannot simply take a function and convert it into a text (String).

func makeIncrement() -> (Int -> String) {

Says that you want to return a function that takes an Int as a parameter and returns a String

You must create such a function first:

func addOneAsString(number: Int) -> String {
    return String(1 + number)
}

And then return it:

func makeIncrement() -> (Int -> String){
    func addOneAsString(number: Int) -> String {
        return String(1 + number)
    }

    return addOneAsString
}

See Swift Reference - Functions