Swift, in my opinion, is a huge improvement over Objective-C. If you’re a developer out there who’s never made an iOS app, now is the perfect time to get into Apple development. Although I am not actually a fan of developing for iOS (more on that to come in the next post), since Swift was just released last year, almost everyone in the iOS development world is relatively new to the language.

If you’re getting into iOS development with a web developer background like myself, MOST of the syntax you will recognize. I think of Swift as sort of like combining PHP, JavaScript, Python, and a few other languages together. However, there are some things in Swift syntax that will really throw you off.

One of the biggest differences to me and many others around the internet is the introduction to ? (question marks) and ! (exclamation points). You will see these thrown around a lot. For example, in Swift, a <code>String</code> is different than a <code>String?</code>. So what is the difference?

Let’s take a common example. I want to write a function that returns a few NSUserDefaults (“Settings” in the iOS world).

//GET USER SETTINGS
    func getUserSettings() -> [String?] {
        let userSettings = NSUserDefaults.standardUserDefaults()
        let settingOne = userSettings.stringForKey("settingOne")
        let settingTwo=userSettings.stringForKey("settingTwo")
        let settingThree=userSettings.stringForKey("settingThree")
        let returnArray = [settingOne,settingTwo,settingThree]
        return returnArray
    }

If you look at our return type you will see I declared it as a [String?]. If I were to declare the return type as a [String] it would not compile. The reason is by default, Swift does not allow optional values. A String must be a String. This even means a String can’t be null (or nil in Swift syntax). When you see a ? at the end of a variable that means you are declaring it as an OPTIONAL. Optionals CAN have null values, but when using optionals, you have to handle them differently.

For example, inside that function, if we were to run:

println(settingOne)

It would NOT output the value of setting one.

Instead you would get an output similar that looks like below:

Optional("VALUE OF SETTING ONE")

So how do we get rid of that ugly looking Optional() wrapper? That’s where our exclamation point comes in!

Now, if we ran

println(settingOne!)

the output would output what we were expecting:

"VALUE OF SETTING ONE"

TL;DR (Too Long Didn’t Read)

A ? (question mark) in Swift allows an Optional value (EX: String?) and the exclamation point makes sure you only get the value inside the Optional() block.

Hope this helps! Feel free to comment!