iOS – A simple introduction to Swift

I don’t know who once said these words, but they apply without question to this blog post.

Make everything as simple as possible – but not simpler.

Anyways, if you have nothing better to do with your day, you might as well learn how to program using Apple’s shiny new language called Swift. Granted it is not so shiny because it has been a while since it was born. But it is still somewhat of a toddler and lots of fun to play with – although this toddler is a lot smarter than what you might think.

Ok – so this post is not about to teach you how to program – or about how to write apps for iOS. It is more of a visual inspiration to start coding in Swift for those still reluctant to make the leap from good old Objective-C. Yes, I am one of those who fell in love with and still love Objective-C. I was particularly shocked when I just found out what Swift is going to do to the increment operator ( i ++ ). But you can read about that elsewhere if you don’t already know.

Enough chit chat – let’s get to the point. Here we go:

Screen Shot 2016-06-20 at 11.00.58 PM

The project here has a single button and a label. The label begins life with the number 1. Pressing the button doubles the value of the label and this keeps happening forever. I have not checked what happens if you keep doing this for a long time. Your finger may not like it much.

1…2…4…8…16…32…you get the idea.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var label: UILabel!
    
    var i = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func buttonPressed(sender: AnyObject) {
        i += i
        label.text = String(i)
    }
}

Granted, this is a really simple app – but hey, we got to start somewhere and this is as good a place as any.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *