Optional Punctuation in Swift

All of the punctuation in Swift looked pretty weird to me until recently, but now that I get it, I’ve really learned to appreciate how great the syntax actually is. The way I think of it is this: if you’re using ?, you’re asking a question, and when you use ! you’re asserting that you already have the answer. Of course, for the second case, you need do need to be sure or your app will blow up.

So, for example:

Asking a Question

if let foo = dictionary["foo"] as? String { ... }

Is the value for the key “foo” a string? If so, assign it to the constant foo.

delegate?.objectDidSomething(self)

Do I have a delegate, and can it respond to objectDidSomething:?

Making an Assertion

managedObjectContext!.save(&error)

I know that managedObjectContext is not nil.

let foo = bar as! String

I know bar is a string, so nothing will go wrong casting it.