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?

Kalem Jones
Kalem Jones
2,115 Points

Stuck on Optional Challenge 1.

So I've been flying through my levels, but I'm totally stuck on the Optional challenge !. Any help?

2 Answers

Chris Shaw
Chris Shaw
26,676 Points

Hi Kalem,

Optionals in Swift are anything that can be of a specified type or nil, the way we specify an optional is by using a question mark after our return type and then set up our logic to return a truthy value which is something other than nil, after that we can then return a nil value which defines the optional logic.

Example

func myAge(name: String) -> String? {
  if name == "John" {
    return 20
  }

  return nil
}

if let age = myAge("John") {
  println(age)
} else {
  println("Incorrect name given, optional triggered!")
}

What does the above do?

In the above example we have our function, as explained earlier optionals are achieved by using a question mark after our return type which in this case is String, next we define our main logic within our if statement which checks to ensure the persons name is John and if they are it returns 20, if this condition isn't met the optional triggers and returns nil instead.

Next we call the myAge function within an IF LET statement which is how we check for an optional value, in this circumstance the keyword let is the value assignment and is used to check whether the value of age has been assigned nil and from them it pretty much becomes a Boolean comparison.

Because our example is passing John as the first argument we should get 20 in console whereas if we changed that to something like Jane we would get the println saying we gave it an incorrect name.

Hope that helps and happy coding.

Kalem Jones
Kalem Jones
2,115 Points

Thanks so much Chris.