Some Things I Learned With Swift


Lately I’ve been hard at work learning the in and outs of Swift 3. Now that I’ve finished 3 apps in the language I feel comfortable enough to share a few things I’ve learned in Swift.


I can’t say whether or not what I’ve been doing in terms of organization is best practice but it looks neat to me, and for the time being, that’s good enough.

Extensions are Sweet

In swift, Extensions are so easy to implement I find myself using them every where. Mostly I’ll use them inside a class to separate portions of code. In Objective-C I would have used the #pragma mark, but in Swift I tend to use the // MARK: – combined with and extension for new sections of code. I’ll typically make a section for properties, styling, and actions to name a few.

View Controller Organization

As of today, I like to use the following format for a new view controller:

    // MARK: - Properties

    class ViewController: BaseViewController {

    fileprivate var cellIdentifier = "CellID"


    // MARK: LifeCycle

    extension ViewController {

        override func viewDidLoad() {

            // Do any additional setup after loading the view.

    // MARK: Actions

    extension ViewController {


    // MARK: Styling

    extension ViewController {

        func setupStyling() {


As you can see I like to keep properties way at the top, then create an extension for the “LifeCycle” operations like viewDidLoad. Notice also that I use the special designation “fileprivate” for swift 3. This allows extensions inside the same file to access those private variables if you happen to be practicing defensive coding.

Almost every view controller has actions and styling. So I’ll add sections for those.

One thing not show here is datasources and delegates. Which I’ll also use an extension for. Here’s some boiler plate code I use often. I recommend making a snippet from this with an auto complete.

    // MARK: - UITableViewDelegate

    extension ViewController: UITableViewDelegate {

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


    // MARK: - UITableViewDataSource

    extension ViewController: UITableViewDataSource {

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return array.count

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? CustomCell else {
                return UITableViewCell()

            // Do something with this cell

            return cell

And this is what my file overview looks like.

How my Swift File looks

How my Swift File looks


Isn’t it pretty? Maybe it’s just me.

View Organization

Since I’m at it, I might as well show how I typically organize views:

// MARK: - Properties

class CustomView: BaseView {


// MARK: - Lifecycle

extension CustomView {

    override func awakeFromNib() {


    func baseSetup() {


// MARK: - Styling

extension CustomView {

    func setupStyling() {


In most views, I like to create a baseSetup method/function that is called from either a custom initializer or the awakeFromNib file. Inside the baseSetup I almost always handling view addition, constraints, and call any styling methods.

Tuples Are Neat

Ok, when swift first came out, I thought to myself. Hmm, tuples are neat, but when will I ever use them!? Well, after playing around a bit, I find them quite useful, and certainly less verbose than an NSDictionary. Unlike an NSDictionary I can hold any item, primitive or otherwise. Eg Int, NSString, String….

So, there are plenty of types of tuples you could make, but a good case might be as a return to a server request:

func someRequest(url:String) -> (httpCode: Int, response: String) {


For now we’ll assume this is somehow synchronous. But, you can see how this would be helpful and you could use it like this:

let result = someRequest("http://someAwesomeAPI")
let code = result.httpCode // Maybe a 404?
let response = result.response

I find I use the Tuple all over the place when I need a boolean response like a failure combined with the data.

Closures Are Fantastic

I won’t go deep into closures now as there is a lot they can do. If your familiar with Objective-C their similar to blocks, but can do a lot more. If your not familiar with blocks, then think of a closure as a function that you can pass around like a variable and execute on command from anywhere.

Instead of the typical delegation pattern I often make a configuration function on a class that accepts a closure like so:

class someClass {

    var aClosure: ((Bool)->())?

    func configureWithAction(_ action: (Bool)->()) {

        let aClosure = action

    func aFunctionForCallingTheClosureAction() {

        let failed = true
        if let aClosure = aClosure { // unwrapping the optional

And Some other class can receive the action like so:

func viewWillAppear(_ animated: Bool) {

    let someClassInstance = SomeClass()
    SomeClass.configureWithAction({ (failed) in // failed is a variable I chose, but you can choose anything.

        //Hey! I bet failed == true !
        // do something with the the failed boolean

And the Final bit to this tips and tricks article is how you can awesomely use structs to define and organize things. I use them all the time in extensions of classes like UIColor.

Here’s a handy UIColor extension I created for FlatUI colors found here:

// MARK: - Helper Methods
extension UIColor {

    class func colorFromRGB(_ rgbValue: UInt) -> UIColor {
        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)

// MARK: - Defined Colors

extension UIColor {

    struct flat {

        // turquoise
        static let turquoise = UIColor.colorFromRGB(0x1ABC9C)
        static let greenSea = UIColor.colorFromRGB(0x16A085)

        // Greens
        static let emerald = UIColor.colorFromRGB(0x2ECC71)
        static let nephritis = UIColor.colorFromRGB(0x27AE60)

        // Blues
        static let peterRiver = UIColor.colorFromRGB(0x3498DB)
        static let belizeHole = UIColor.colorFromRGB(0x2980b9)

        // Purples
        static let amethyst = UIColor.colorFromRGB(0x9B59B6)
        static let wisteria = UIColor.colorFromRGB(0x8e44AD)

        // Darks
        static let wetAsphalt = UIColor.colorFromRGB(0x34495E)
        static let midnightBlue = UIColor.colorFromRGB(0x2C3E50)

        // oranges & yellows
        static let sunFlower = UIColor.colorFromRGB(0xf1C40f)
        static let orange = UIColor.colorFromRGB(0xf39C12)

        static let carrot = UIColor.colorFromRGB(0xE67E22)
        static let pumpkin = UIColor.colorFromRGB(0xD35400)

        // Reds
        static let alizarin = UIColor.colorFromRGB(0xE74C3C)
        static let pomegranite = UIColor.colorFromRGB(0xC0392B)

        // Lights

        static let clouds = UIColor.colorFromRGB(0xECF0F1)
        static let silver = UIColor.colorFromRGB(0xBDC3C7)
        static let brightWight = UIColor.colorFromRGB(0xFFFFFF)

        // Grays

        static let concrete = UIColor.colorFromRGB(0x95A5A6)
        static let asbestos = UIColor.colorFromRGB(0x7f8C8D)

With the first extension we’re allowing the definition of colors from RGB. The second struct “flat” defines a bunch of colors.

So for example, you can call a blue color like so:

let someLabel.textColor = UIColor.flat.peterRiver

Pretty neat huh?

Structs Vs Classes

One more thing before we sign off on this article is when to use a struct vs a class. Both basically behave the same, but the convention is basically this; Classes are for subclassing. If you do not plan on subclassing use a struct instead.


Objective-C and Swift Comparison

This week I thought I would share some notes I took on the differences between Objective-C and Swift at basic level. IE chapter one of Apple’s Swift Programming Language iBook. I encourage you to go download it for free if you haven’t already.

The set of note offered here were just some notes I took while reading the first chapter, I haven’t gone back and edited so proceed with caution.

Anyway, without further ado:

Objective-C and Swift Comparison

Swift Optionals

As an Objective-C developer, the biggest point of confusion for me was with optionals. There are of course other tricky idiosyncrasies, but the hardest thing to wrap my head around was the use of optionals and what the hell “?”,”!”, and “??” means.

Why We Needed Optionals

If you are at all familiar with objective-C , then your well aware that every object had the option of returning nil. To make code safe, we had to typically check for nil all of the time. Often we would set a return nil when something went wrong as well. So we would end up with a bunch of ugly code that looked something like this:

- (NSString *)getStringItemFromResponse:(id)responseObject {
    if([responseObject] != nil && [responseObject isKindOfClass:[NSDictionary class]]){                        
        return responseObject[@"someItem"];


    return nil;

Notice that we return nil here if we fail to return a string by the end. Also notice that I purposely left out a check to ensure that responseObject[@”someItem”] is not nil and it is actually an NSString. Although we try to be perfect, most of us forget to do this sort of check from time to time. Swift can help with this.

How Can Swift Help?

When you define something as optional in swift, for instance the return would be a string optional, we’re saying this will either be a string or nil. This means, swift will force you to handle the condition where responseObject[@”someItem”] may be nil.

Now let’s consider a swift example of somewhat similar code:

func getStringFromResponse(responseObject:Any?) -> String? {

    if let tmpResponse = responseObject as? [String:String] {

        return tmpResponse["someItem"]

    return nil

Here we’ve created a method that can take any object as an optional and it will return a string optional. Also, notice with swift you can declare a variable within the if statement. This is called optional binding. This variable will be a non-optional result inside if statement if evaluates to true. This result can then be used inside of the if statement.

First we can take the any object and make a variable within an if statement to check if the response object is a dictionary that contains only a string key and a string value. If that is true, we will return tmpResponse[“someItem”], which will return only a string value because our check. If none of that passes the if statement we’ll return nil. For this method to pass, you’ll have to make sure your dictionary type is [String:String]. This is a little more elegant and easy to read than the last response, but more importantly, all nil conditions and proper return types are guaranteed.

This example works if we expect the anyObject dictionary that comes in to have the type [String:String]. But what if the dictionary contains any object or primitive with a string key? For example [String:Any]

Well swift will let us handle that too!

func getStringFromResponse(responseObject:Any?) -> String? {

    if let tmpResponse = responseObject as? [String:Any]{

        return tmpResponse["someItem"] as? String

    return nil

Or equivalently, and perhaps a little better:

func getStringFromResponse(responseObject:Any?) -> String? {

    if let tmpResponse = responseObject as? [String:Any],
        let tmpResult = tmpResponse["someItem"] as? String{

        return tmpResult

    return nil

A Little More on Optional Chaining and Optional Binding

In the previous examples, you saw the use of optional binding in the if statements.

In Objective-C if you tried to operate on variable with a nil value, then you would crash. For example:

UILabel *someLabel = nil;
UILabel.text = @"Some Text"  //< -- Insta Crash :(

In Swift however, this it totally good if you define the label as an optional.

let someLabel: UILabel? = nil < -- the question mark makes it an optional.
someLabel?.text = "Some Text" < -- If nil, the text setter wont ever be attempted.

You can also keep chaining these

let someView: UIView? = nil
let cgColor = someView?.tintColor?.CGColor < -- cgcolor will be nil

So in this last example if someView is not nil, but tintColor is nil, then CGColor doesn’t get attempted. Swift is super safe (If done right :]).

From the cgColor example, if all you want is cgColor then you can use the optional chaining method we used. However, if you plan on accessing multiple elements of an optional, its better to use optional binding like so:

if let view = someView, let color = view.tintColor {



Here I’m not doing anything with the values, but you can see how optional binding is safe and helpful. If view evaluates to a non-nil value and color (which is derived from that previous value) is also non nil; than this if function will proceed. You can easily access each of the variables that have guaranteed values.

WTF is This “!” For?!!?

When working with optionals, you’ll probably make some mistakes and the compiler will suggest placing an exclamation point next to your optional. This is typically a bad idea. The exclamation point force unwraps the optional, and basically removes the optional protection. You’re basically saying, “It’s all good! This variable definitely is not nil”. Remember that Objective-C example with the nil label? Well this is basically the same thing. Just to be thorough though:

let someView: UIView? = nil
let color = someView!.tintColor < -- Insta Crash :(

For the most part, don’t use em. You can almost always use optional binding instead.

The main exception is when you define a class variable that is a foundation framework type (eg. UIButton, UIView, NSDate) without an initial value. These typically get defined as:

@IBOutlet var mainButton: UIButton!

This is because you are bridging over an Objective-C type. nil in swift is different from Objective-C, in Objective-C nil is a pointer to a nonexistent object. In swift, nil is not a pointer but rather the absence of a value. In other words, an Objective-C object always has a value and that value is a pointer. That value may be a pointer to a valid object, or a pointer to a nil object. So we implicitly unwrap it so we aren’t constantly having to unwrap it every time we use it. This would be super annoying. Implicitly unwrapping bridged Objetive-C elements is a compromise to make our lives easier. Take note though, you will still need to initialize these before using them.

Final Thoughts

When I first saw optionals, I didn’t care much for them. They seem to be a hassle, but once you take the time to really understand them, they actually turn out to be a time saver. Not to mention I have noticed most classes have substantially less lines without all the checking to make sure a value is not nil.

State of The Union

The presidential state of the union is a designated time where the president can openly complain about his views on the world and update us all on what is going on in his world. Since that is basically what I’ll be doing in this article, that is the title I gave it.

A Brief History

I had spend quite a bit of my free time for roughly a year or two learning Objective-C. Granted, had my day job been working on Apps, I could have learned it a bit quicker. Now that I am a gainfully employed iOS developer I have a few more years of experience under my belt. So imagine my frustration when a new programming language emerges just as I was starting to touch on Objective-C Mastery.

I started NSCookbook with a basic goal. NSCookbook was a method of teaching myself iOS Development while also providing value to the community. I have always found that the best way to learn something is to teach someone else how to do it. As a noob myself, I felt I had a unique perspective that would help out the new comers. What I liked about learning iOS development is everything was new to me and it was fun. Now that I’m more experienced, most of what I will write now is something I already have a pretty good grasp on. In other words, It’s getting a bit boring to me. This is where Swift will help me out.

The State of Swift

Swift 1.1 came out with XCode 6.0 and iOS 8. At the time I had guessed that Swift would not be quickly adopted as it was relatively new and buggy. None-the-less, folks adopted Swift in surprising numbers. As of Today, Swift 2.0 is the current version, and is quickly becoming the standard iOS language. This has become an increasingly cumbersome fact for an Objective-C developer for the following reasons:

  1. Every time I’m trying to solve problem that is new in iOS 8 or iOS 9, Most of the solutions that come up in stack overflow are now swift.
  2. New libraries on Apple’s documentations are documented in Swift
  3. Playgrounds are really sweet for experimenting, and they don’t support Objective-C
  4. Once you see Swift, you may realize how much more ugly Objective-C is.

So What Now?

I have noticed That I have been increasingly lazy with respect to my articles. This is mostly because I don’t like the idea of showing both Swift and Objective-C. It’s a lot of damn work, and half of it is largely uninteresting to me. Therefore, Moving forward I’m going to Ditch Objective-C. My primary objective right now is to learn swift. As such, I’d rather not waste too much time with Objective-C. I will however attempt to update old articles that are still applicable with Swift. I hope ya’ll are okay with that. 🙂

iOS Programming Recipe 36: A Fixed Width Dynamic Height ScrollView in AutoLayout

As an iOS Developer it seems I come across a common situation where I want to add a content view with the same width as the screen inside a scroll view. Since most apps need to have responsive layouts, this usually makes sense to do using Autolayout. At first when learning about scrollviews, they seemed like magic. Due to their slightly different rules they were also a bit frustrating.

[Read more…]

Privacy Policy