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?

Exact same code; not getting a struct.

import UIKit

func findApt (aptNumber : String) -> String? {
    let aptNumbers = ["101","202","303","404"]
    for tempAptNumber in aptNumbers {
        if ( tempAptNumber == aptNumber) {
            return aptNumber
        }
    }
    return nil
}

let culprit = findApt("404")

The code I'm using is exactly like Amit's but I'm getting just 404 in the console, not Some 404 like he's showing. Please explain why without assuming I know what I struct is. I haven't gotten to that lesson yet.

Philippe C么t茅
Philippe C么t茅
1,850 Points

I have the same "problem" here. It could be related to the fact that we are now using Swift 1.2. I cannot say exactly what is happening. Anyone have any clues on this?

2 Answers

Philippe C么t茅
Philippe C么t茅
1,850 Points

It looks like it is indeed related to the fact that we are using Swift 1.2 today. The class was recorded with Swift 1.0.

Some of those changes are explained here:

"When Swift was first released, every call to a Cocoa API method took and returned implicitly unwrapped optionals (i.e., AnyObject!). Because they crash a program on access, implicitly unwrapped return values are inherently unsafe if there isn't clear documentation of whether or not a method will return a null value. All those exclamation marks were a sign of bad form. Sure, Swift bridged to the Cocoa APIs, but it sure looked grumpy about it.

As the beta releases rolled on through the summer and fall, internal audits gradually removed the offending punctuation, replacing implicitly unwrapped optionals with either true optionals or non-optional, never-gonna-be-nil values. This vastly improved the experience of working with Cocoa, but there was no mechanism to mark up third-party code in the same way, leaving part of the problem in place.

But no longer鈥擲wift 1.2 ships alongside a new version of Clang. New property attributes and pointer annotations allow you to indicate whether a pointer, be it an Objective-C property, method parameter, or return value, can or won't ever be nil."

http://nshipster.com/swift-1.2/

Thanks, Philippe. I never would've considered this factor. Thought I was doing something wrong!

Philippe C么t茅
Philippe C么t茅
1,850 Points

You're welcome! This problem was bugging me as well to be honest... ;)