Last updated by at .

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.

 

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 {

    print(view.description)
    print(color.description)

}

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.

5 More Tips and Tricks

The last few posts have been pretty long and drawn out, so this time we’ll make a short and sweet post that helps save you some time. Building on the past tips’n’tricks article, here’s a few more.

Assumptions

[Read more…]

Memory Management Part II

In part one of this series we talked about the heap, the stack, object ownership, and how reference counting works. In this article we’re going to expand on this to include the role of properties and how all of this works in ARC (Automatic Reference Counting).

[Read more…]

Memory Management Part I

Not too long ago I came under the painful realization that I had been hacking my way through iOS apps without fully understanding how Memory Management works in Objective-C. Up to this point my memory management tactic was waiting for the compiler to complain and then take the suggestion the compiler provided. If that failed, Stack Overflow to the rescue! While this usually fixed the problem and works fine on small applications, it probably isn’t the best tactic when working with apps of a larger scope where performance is a big issue. So hopefully with this article I can help clarify things for you so you’re not left stuttering stupidly in an interview when they ask “What’s the difference between the stack and heap?” or “How does reference counting work?”.

[Read more…]

5 Time Saving Tips In Xcode

Working with Xcode can sometimes be a frustrating experience…

However, Xcode has a few times saving features that really make a difference in day to day development. In this post we are going to break from the traditional format in order to examine a few of these features.

1. Snippets

Xcode snippets have gotten a bad wrap since they were introduced. This is mostly because they seem to lack some obvious features and are poorly documented. However, this doesn’t stop them from being an immensely powerful addition to Xcode. So let’s dive into using existing snippets and creating new ones.

[Read more…]

Development Tools – Opacity

Assumptions:

  1. It isn’t required, but it will be helpful if you are familiar with layer based image editing or have experience with a graphics editing program such as Adobe Photo Shop

Getting Started

A important aspect of developing apps for iOS or OS X is creating a great User Interface. Even if your app has all the latest and greatest functionality, you are going to have a hard time getting anybody to use it if it is lacking in the UI department,.

Opacity to the rescue!

Opacity is a layer based vector graphics application for the Mac that makes designing graphics for your app a breeze. Opacity has built in templates for skinning buttons, creating 1x and 2x resolutions non-retina & retina devices, and many other time saving features as you will see!

Step 1: Download Opacity

Currently (as of this writing) Opacity is not available through the Mac App Store and I’m not sure if the developer has any plans to add it any time soon, however it can be downloaded at http://likethought.com/opacity/. I recommend starting with the trial version (free), but the full version will be necessary to remove a pesky watermark from your exported images (currently the full version is $89.99).

Additionally, there is a great video tutorial on the home page that I would recommend watching before moving on to Step 2.

Step 2: Creating a UIButton Image

Lets get started!

[Read more…]

Familiarizing Yourself With Xcode

This post is a quick rundown of the Key Elements of Xcode and a quick start guide to a Hello World App. I won’t get into all of the nitty gritty details of what Xcode can do, but I will provide some information on the most useful bits of Xcode.

Assumptions

  • You Have Already Installed Xcode 4.5 . If not Please do so.

Creating A Project

After opening Xcode and creating a new project you will be presented with a number of template options for the new iOS project. As a beginner, the Single View Application will be most useful to you. As a Starting point, a lot of Developers tend to use A single View Controller or a Empty Application instead of the other options.

Select Single View Application and press Next.

The next Screen will be for Project Options. The Product Name is the most important Field here as it will be the project name. Fill in the Organization and Company Identifier. These fields are arbitrary while learning but Xcode still requires them. Make sure the “Use Storyboards” and “Use Automatic Reference Counting” check boxes are checked. Since we’re doing an iPhone App choose iPhone from the devices drop down.

[Read more…]

5 Steps To Beginning App Development

Assumptions:

  1. You’re already familiar with Mac OS X and or iOS, if not I suggest following step 1 below and then familiarizing yourself with the Mac for a bit before continuing on to step 2.
  2. You are familiar with the concept of software and writing code, but haven’t necessarily written any before. If not check out Wikipedia for a quick crash course. http://en.wikipedia.org/wiki/Software & http://en.wikipedia.org/wiki/C_(programming_language) should do the trick!

Step 1: Buy a Mac & maybe an iOS device

If you want to develop apps for iOS (iPhone, iPad, etc.) or OS X (Mac) the first thing you will need is a Mac. While it is possible to develop apps for these platforms without a true Mac, I do not recommend going down this route, especially when just getting started.

I recommend getting a used MacBook Pro 2010 or newer off Craigslist or Ebay if you can’t muster up the cash for a new system! I started with a 21.5in iMac personally, but the portability of the laptop allows you to work away from the house and the coffee shop can be your best friend when writing software.

You will need to install the latest version of OS X (currently Mountain Lion) on the system, and I recommend ensuring it has a minimum of 4gb ram installed.

Step 2: Register for the Apple Developer Program

Registering for an Apple developer account is essential to beginning app development for iOS or OS X. It is very simple, just visit https://developer.apple.com and choose either iOS dev center or Mac Dev Center, then click register.

If you already have an iTunes account (Apple ID), you can link your developer account to that and avoid creating and remembering yet another password. There are a few different types of developer accounts and I won’t go into the details of each one, but you basically have two choices here:

  1. Free program – which allows you access to minimal resources and you can only run your apps on a device simulator
  2. Paid program – $100 per year which gives you access to an abundance of resources and the ability to install your apps on device

If you’re really serious about being an App Developer, I recommend biting the bullet and going for the paid program. In my opinion, not being able to see your creation running directly on your iPhone or iPad is a major disadvantage for a number of reasons. First of all, device testing is essential to developing an app that both looks great and performs well. Secondly, seeing an app that you developed running directly on your device is an awesome experience and one that can be the difference between giving up and carrying on (I would not let yourself pass on that experience if your serious about building apps). However, if you really can’t afford the $100 after throwing down some dough for that new Mac you purchased in step 1, then the free program will get you though the beginner process for awhile, but I would still recommend upgrading as soon as you can.

Another important feature of the paid program is the ability to download/view WWDC videos and sample code (World Wide Developer Conference). These are videos created by Apple engineers detailing the tools and APIs (Application Programming Interface) available from Apple. Many of these videos are of a “how to” format and are essential to developing great apps!

Once you have signed up for your developer account you can find the WWDC videos .and other resources here https://developer.apple.com/wwdc/

Step 3: Install Xcode

[Read more…]

css.php
Privacy Policy