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 Swift Functions and Optionals Optionals What is an Optional?

Benjamin Bell
Benjamin Bell
4,364 Points

Swift vs Scala

Are optionals similar to covariance in Scala?

Also can you use a function as the parameter of a function in Swift? And do things like Currying?

1 Answer

Stone Preston
Stone Preston
42,016 Points

In programming in general, variance relates to subtyping. it is not related to optionals in swift.

An optional typed variable just means it either holds a value or is nil. Non optional variables cannot be nil.

For your second question:

from the Swift eBook

Every function in Swift has a type, consisting of the function’s parameter types and return type. You can use this type like any other type in Swift, which makes it easy to pass functions as parameters to other functions, and to return functions from functions. Functions can also be written within other functions to encapsulate useful functionality within a nested function scope.

so yes you can use a function as an argument/parameter to another. You can also return a function from another function (which is similar to currying i think?)