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.

Organization

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() {
            super.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() {
        super.awakeFromNib()

        baseSetup()
    }

    func baseSetup() {

        setupStyling()        
    }
}

// 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
            aClosure(failed)
        }
    }  
}

And Some other class can receive the action like so:


func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    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: https://flatuicolors.com/


// 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.

 

About Joe Hoffman

I am An Electrical Engineer that spends a lot of my off time doing web development and other programming. Currently I am trying to expand my knowledge with iOS and I find that writing tutorials helps me learn more thoroughly as well as provide some useful info to others.

Speak Your Mind

*

css.php
Privacy Policy