Show Menu

Looking for an iOS Developer?

Submit your 30 day Job Listing for FREE

iOS Development Swift Tutorial

Apple recently announced a pretty major change to the way iOS apps have been developed in the past, an entirely different programming language called Swift which replaces Objective-C. In my efforts to learn the new language, I’ve decided I will be posting regularly as I step through the learning process, sharing everything I find. This is the first post of many on the topic, and I hope you decide to follow along!

Are you wanting to build a Swift application that connects to a server? You might be interested in this back-end tutorial with Parse.com: Swift: Create user sign up based app with Parse.com using PFUser

This article is part of the create iOS8 Applications with Swift tutorial series, here are the other published articles:

    It is highly likely that much of the code examples here of Swift will be changed later. This is partially because my development style is to write now to test an idea, and refactor later, and it is partially because I (like everyone) am completely new to Swift and am starting out fresh. So it is likely as I learn things over time, the course of this tutorial will change. I will update code examples as needed, but not so much that the learning process is not also demonstrated. I think this is also a useful process to see.

    So I’m going to start with a pretty basic app and explain how the code works. Ready? Here we go…

    The Basics

    iOS8 Swift does away with the standard of declaring variables by starting with their type names, and instead opts to use a Javascript-like ‘var’ keyword to define any variable.

    So for instance in Objective-C where you have this:

    
    NSString *myString = @"This is my string.";
    

    Whereas now, in iOS8 Swift you now have this:

    
    var myString = "This is my string."
    

    Meanwhile constants are expressed with the ‘let’ keyword

    
    let kSomeConstant = 40
    

    In this case kSomeConstant is implicitly defined as an integer. If you want to be more specific you can specify which type it is like so:

    
    let kSomeConstant: Int = 40
    

    With both arrays and dictionaries, they are described using brackets []

    
    var colorsArray = ["Blue", "Red", "Green", "Yellow"]
    var colorsDictionary = ["PrimaryColor":"Green", "SecondaryColor":"Red"]
    

    There’s a lot more to go over, but I think these basics are important to get a start going on to the tutorial. So with that, let’s move on to Hello World.

    iOS8 Hello World in Swift

    First, we’re going to write the simplest app imaginable to get started, Hello World.

    Our iOS 8 Hello World application will only do one thing: print “Hello World” to the console. You’ll need a developer copy of Xcode in order to follow along, which requires a developer account. If you have one, head on over to http://developer.apple.com and get your copy before we begin.

    So, now you’ve got your Xcode IDE (Integrated Development Environment) set up. Let’s write hello world out to the console. This example demonstrates the simplest app that can be built, and more importantly shows that your environment is set up correctly.

    Set up a new Xcode project using the single-view application template, and make sure you opt for Swift as the language.

    You should now find an AppDelegate.swift file in the project hierarchy. Inside of this file find the line that says:

    “// Override point for customization after application launch.”

    Replace this line with our amazing hello world code:

    
    println("Hello World")
    

    Now press run and you should see a blank app boot up, and the words “Hello World” print to the console. Congratulations! You just wrote your first iOS8 Hello World application in Swift! This app probably won’t win any awards, let’s trying doing something a little deeper…

    Adding a Table View

    In this section, we’re going to actually put some stuff on the screen, yay!

    Open up your Main.storyboard file in Xcode and lets drag in a “Table View” object from the Object Library. Position this fullscreen in your app window and make sure it lines up with the edges. If you run the app at this point, you should see an empty table view in the simulator.

    Now we need to set up a delegate and data source for the table view. This is easy to do in interface builder. Just hold control, and then click and drag from the tableview to the “View Controller” object in your storyboard’s hierarchy, and select ‘data source’. Repeat with the ‘delegate’ options.

    Okay, now let’s dig in to the protocol methods for Table Views. Because we’re using the UITableViewDataSource and UITableViewDelegate in our view controller, we need to modify the class definition to say as much.

    So open ViewController.swift and modify this line:

    
    class ViewController: UIViewController {
    

    to this:

    
    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    

    Command+clicking on either of these protocols will show the required functions at the very top. In the case of a tableview, we need at least these two:

    
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    

    So let’s modify our View Controller class by adding these two functions

    
    
    func tableView(tableView: UITableView!, numberOfRowsInSection section:    Int) -> Int {
    return 10
    }
    
    
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
    
    cell.text = “Row #\(indexPath.row)”
    cell.detailTextLabel.text = “Subtitle #\(indexPath.row)”
    
    return cell
    }
    

    The first method is asking for the number of rows in our section, in this simple iOS 8 Hello World tutorial we just hard-code 10, but normally it would be the length of an array controller. This example is intentionally simple.

    The second method is where the magic happens. Here we create a new instance of a UITableViewCell called cell, using the Subtitle cell style.

    Then, we assign the text value of this cell to the string “Row #\(indexPath.row)”

    In iOS8 Swift, this is how variables are embedded within a string. What we’re doing is retrieving the value of indexPath.row by inserting \(indexPath.row) in to our string, and dynamically replacing it with the row number of the cell. This allows results such as “Row #1″, “Row #2″, etc.

    The detail text label is only available in the Subtitle cell class, which we are using here. We set it similarly to “Subtitle #1″, “Subtitle #2″, and so on.

    Go ahead and run your iOS8 Hello World app and you’ll now see an amazing list of cells with titles and subtitles indicating their row numbers. This is one of the most common ways to display data in iOS, and will be sure to serve you well. For the full code to my View Controller file, take a look here:

    
    import UIKit
     
    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
                                
        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.
        }
        
        func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
            return 10
        }
        
        
        func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
            let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
            
            cell.text = "Row #\(indexPath.row)"
            cell.detailTextLabel.text = "Subtitle #\(indexPath.row)"
            
            return cell
        }
     
     
    }
    

    That’s it, You have successfully created an iOS8 Swift Hello World application and also done a few extra things. In part 2, we’re going to explore using the iTunes search API to create an app capable of finding and displaying albums within the iTunes store.

    having issues?

    We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

    Ask Question

    FREE Download!

    Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


    Sharing is caring

    If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


    Written by:

    I am an app developer in Austin, TX. I spend time dabbling with iPhone, iPad, Android, and web technologies. I write about technology, startups, and my technology & entrepreneurial experiments. More of my Swift Tutorials can be found on my site.

    Comments

    comments