Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Closures in Swift 2 First Class Functions Functions as Data

Kevin Gutowski
Kevin Gutowski
4,082 Points

Why didn't we specify what the optional parameter was for someFunction?

When we defined someFunction's optional parameter as String, why wasn't it defined as (aString: String) to match the original printString function?

let someFunction: String -> Void = printString
someFunction("Another string")

vs

let someFunction: (aString: String) -> Void = printString
someFunction(aString: "Another string")

1 Answer

Jeroen de Vrind
Jeroen de Vrind
29,772 Points

If you declare the type of the constant 'someFunction' you only specify it's type: String -> Void. Your second example is not a type declaration and I'm sure the compiler will give an error. Here you've put an parameter as if you declare a concrete method. So things are mixed up.

The type of someFunction is String -> Void, so you can assign a method of this type to this constant. 'printString' is a method of this type:

func printString(aString: String)

is of type String -> Void. And when you have assigned this function to the constant someFunction, then you can pass a string as the value for the argument of the printString method as well to the someFunction variable.

someFunction has not an optional parameter String. There are no questionmarks. It's not a function, but a constant which can hold a function of type String->Void