Devarshi
Devarshi

Reputation: 16758

Passing inline function definition as input parameter to a function

Say, I have a function which accepts a function as one of the input parameters:

// modify passed string
func modifyString(paramString: String, modificationFunction: String -> String) -> String {
    return modificationFunction(paramString)
}

Now I can define a function like this:

func addLearningSuffix(inputString: String) -> String {
    var returnString = inputString + " is learning swift"
    return returnString
}

And use it like this:

// adds suffix - is learning swift
modifyString("Miraaj",  addLearningSuffix) // returns "Miraaj is learning swift"

In above case I just passed function name - addLearningSuffix as input parameter to the function - modifyString, but what if I want to define function in the same line while passing it as input parameter.

I know that functions are special case of closures, so I can pass inline closure like this:

// adds prefix - Miraaj
modifyString("is learning swift",{
    (inputString: String) -> String in
    let result = "Miraaj " + inputString
    return result // returns "Miraaj is learning swift"
    })

or like this:

modifyString("is learning swift"){
    (inputString: String) -> String in
    let result = "Miraaj " + inputString
    return result
    }

But why I can't pass inline function definition like this:

modifyString(" is learning swift", func addSomeOtherPrefix(inputString: String) -> String{
    return "Miraaj" + inputString
})

Trying which compiler complains :(

Please suggest if I am doing any thing wrong.

Upvotes: 3

Views: 3733

Answers (2)

onekiloparsec
onekiloparsec

Reputation: 2063

You can, but avoid the func keyword, that is, avoid declaring a fun, but use the anonymous nature of closures:

modifyString(" is learning swift", { inputString in "Miraaj" + inputString })

See http://fuckingswiftblocksyntax.com

Upvotes: 1

Khanh Nguyen
Khanh Nguyen

Reputation: 11132

Think about the difference between declaring an object and then using it:

var a = 100
abs(a)

vs using it directly:

abs(100)

Same difference applies between declaring then using a function:

func talk(x: String) { return x + " is talking" }
doThis(talk)

vs using it directly:

doThis( { x: String -> return x + " is talking" } )

Writing

doThis( func talk(x: String) { return x + " is talking" } )

is like writing

abs(var a = 100)

which doesn't make sense.

Upvotes: 5

Related Questions