Show Menu

Expanding your company? Need a 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

    There are currently: 50 Responses to “Developing iOS8 Apps Using Swift – Part 1- Hello World”. Leave your comment!

    I had a whole bunch of compile errors that I solved by taking the !s out of the method headers, has there been a new version since this tutorial?


    you copied and pasted, replace the ” with “


    Hello, this is a great tutorial but I’m having a little issue, its probably
    just me being simple as I’m only just starting out with this but i keep getting this error –

    Type ‘ViewController’ does not conform to protocol ‘UITableViewDataSource’

    I get this error at the end of this line of code – class ViewController:
    UIViewController, UITableViewDataSource, UITableViewDelegate {

    iphone application development


    Great tutorial mate – I combined yours with this guide and my app is working perfectly… I did the same as a few of the others and got the Table View Controller confused, got there in the end though!


    i have got this error, what is happened? [UIView tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0xb210980


    This look really good but I am not sure that I want to pay $100 just to play with the language. Boo apple


    table view not scrolling even i increases the number of row to 50.


    Hi Jameson,

    It is probably really stupid, but when I drag from the Table View to the ViewContoller.swift file, I get a blue line connecting them and then it disappears? Any ideas? Could you maybe explain in more detail how to do this?

    Thanks
    Ed


      OK so you see those three icons directly above your Main Storyboard ( not the files in the Project Manager ). Try dragging to the left hand one there.


    Thanks for the tutorial. It’s working but my code completion in Xcode isn’t. When I add the protocol details in the class header, both appear in my code completion as expected and I get the warning about not confirming to protocols, again as expected.
    However, when I start to type the required functions:

    func tableView…

    I get no code completion. It recognises the functions once written, and the program works, but some code shows hints e.g. if I type:

    let cell:

    it will show UITableViewCell in the code completion, but later in that line, reuseIdentifier does not show in code completion.

    Do you need to import anything? I’m pretty sure it’s all in the UIKit call.

    Is anyone else have this strange code completion issue?

    Thanks, Mark


      I believe it’s a bug on XCode.
      It would not auto complete on @optional func.

      You could hold command and click on protocol (delegate or datasource) to copy function to your class instead.


    Hi Jamson,

    I have tried everything you mentioned in this tutorial but what I got is only an empty tableview, any advices please?

    Jimmy


      you need to hook up the view controller as the delegate and datasource for the tableview. In the storyboard you can control drag the tableview to the viewController and choose datasource then delegate.


      Jimmy,

      Did you link the tableView’s delegate & database to ViewController @main.storyboard?


    I am not able to print Hello World!
    This is not happening… :(


      It is actually printing. println() outputs text to the console, not to the screen. If you look at the lower center right of xcode in your screenshot you can see your text (or at least I can see some of it).


    Please someone help me with this; I cant get to print Hello world…


    Getting this error “Type ‘ViewController’ does not conform to protocol ‘UITableViewDataSource'”..i have used both protocol in code func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!


    As you mention in tut “make sure you opt for Swift as the language…” can you explain how to choose swift language for xcode 6.


    Weekly-ish


    Hi there ! awesome tutorial, is part 2 already available ?


    What does the ! after UITableView! do?


      the ! indicates an implicitly unwrapped optional.

      if you had:

      let possibleNumber: String? = “123”

      you would have to unwrap it to use the value like:

      println(possibleNumber!)

      otherwise you can tell the compiler that it is optional but it shouldn’t be nil at this point by saying:

      let possibleNumber: String! = “123”

      which would allow you to use it without the ! everytime like:

      println(possibleNumber)


      The ! basically says the variable should not be nil at this point, it’s been validated that this variable exists.


      It “unwraps” it, specifying that it’s not an optional value, and should be *for sure* set to something other than nil


    I am completely new to writing code, so please bear with me.

    When I change to this line

    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    I get an error “Type ‘ViewController’ does not conform to protocol ‘UITableViewDataSource'”

    This doesn’t allow me to edit the ViewController class.


    Is Swift iOS8 exclusive?


    From the syntax it reminds me of Scala. I am yet to dive in the pond, but looking at couple of examples above surely reminds me of scala


    I’d say this makes Dart a functional imperative for Android now.

    I think this is a positive step forward for Apple that solidifies the iOS platform. The functional overtones of the language are unmistakable, and the bridging, almost, seamless.

    Nice work Dev Tech and thank goodness for LLVM


    Hi, great work! Just a point. You should use the dequeueReusableCellWithIdentifier. It would be something like :

    var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier ) as? UITableViewCell

    if cell == nil

    {

    cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)

    }

    cell!.text = “Data: (indexPath.row)”


      Thanks David! I was actually aware of this practice from my Obj-C days, but wanted to keep it simple. Part 3 will make use of reusable cells :)


      Hi, David. I’m quite new to this stuff. Could you explain why one should use your “dequeue” variant?
      And thanks a lot to Jameson for writing this article!


        It is much more memory efficient, as it will reuse cells after they scroll off the screen. I.e. it will only need as many cell objects as can be shown on the screen at once, rather than the number of items in the table.


    Heh. My first Swift test was a basic table view controller too, exactly like yours. I even returned a cell with text = “Row (indexPath.row)” :) Then I added an array to the class, and had didSelectRow… perform a segue to a new viewcontroller. Then I added some gcd background stuff, just to see how that translated over. All so simple, all very clean. Really going to enjoy writing apps in Swift (not that I minded Objective C too much, but Swift feels very nice).


      Hey Adrian, sorry a little off topic year, but I recently started learning objective C(a week before WWDC) and I am little confused as to continue with it. Is objective a prerequisite to learning Swift? I am a user experience designer and my only coding experience is C and C++ back in college. Thanks


        No problem. Objective C is not a prerequisite to learning Swift, but it’s probably easier right now (because all of the existing help that you’ll find out there is related to Objective C). The real problem is not the language, but the need to learn the iOS API and how things hang together.

        For example, you need to know that to display data in a table, you have to add a table to your view, connect it to a variable in your class, implement UITableViewDataSource in your class, and create at least two methods (numberOfRowsInSection and cellForRowAtIndexPath).

        You can do all of that in Objective C, with a bit more boiler-plate code (and syntax that lots of developers used to other languages like Java find off-putting), and now you can do it in Swift, which is slightly simpler, but less well documented (that will change as more people move over to Swift – and I’m pretty sure they will move over).

        Anyway, as you can see, knowing the things that you need to do to display data in a table is pretty much the same either way, so your learning curve is probably going to be quite similar which ever language you choose. I think I’d still choose Objective C, if I were learning right now, today, and once you start finding good Swift tutorials appearing, switch over and relearn the basics again in Swift. That way, you’ll get to re-digest what you’ve already learned and really cement that knowledge. That’s the key to learning to code well — lots of repetition with simple projects. Each time you do something, it’ll become clearer.

        And don’t be put off it it seems hard going at first. I’m an experienced programmer, but when the iOS SDK first came out (in 2009?) it took me over a month of regular working at it before I became even vaguely comfortable with the SDK and Objective C. I remember how incredibly different it all felt, and there wasn’t much help out there at the time (just one forum built by some highly-talented jailbreakers, who had worked the entire API out themselves before Apple built the official SDK). Things are far better now, and there’s so much more help out there (Stack Overflow, for instance), but it’s definitely a learning process.

        Good luck anyway; once you’re over the hump you’ll look back and be very happy that you did it.


          Thanks a ton! I have been wandering online trying to get a perspective. This helps me a lot and puts my mind at ease. I can get back to learning now. Much appreciated!


      Agree, in part 2 I use the iTunes search API to actually pull in some results. Part 3 will have the interaction.


    Leave a Reply

    Would you like to sign up to the mailing list by our sister site: SwiftMonthly?