TableView Tutorial in iOS8 with Swift

In this tutorial we will display a Table View with some rows filled with data. We will use Swift as the language of this tutorial, so Xcode 6 is required to follow along. Xcode 6 can be downloaded at Apple's developer portal.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftTableViewTutorial and then fill out the Organization Name and theOrganization Identifier with your customary values. Choose Swift as Language and iPhone as Device.

Go to the Storyboard and drag a Table View on top of the main view. The Storyboard should look like this.


Ctrl and drag from the Table View to the View Controller in the Document Outline and select the dataSource outlet. Repeat this for the delegate outlet.

In Swift there are no separate header and implementation files, the whole View Controller class is defined in the ViewController.swift file. Go to this file and right after the class ViewController: UIViewController {  line add a constant containing some data for the table rows.

let tableData = ["One","Two",Three"]

Swift has inferred the constant as an Array of Strings. Next, set the number of rows in the tableView:numberOfRowsInSection function. Add this function before the closing bracket of the class.

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int 
  return self.tableData.count;

Our Table View will have 3 rows according to the count method of the Array class. Note in Swift a class method is called using the dot syntax. Next, implement the tableView:cellForRowAtIndexPath function

func tableView(tableView: UITableView!,
        cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")      
    cell.textLabel?.text = tableData[indexPath.row]
    return cell 

Each Row will have a default tableview-style and will have the values of our tableData array. In Swift the intializer method names are truncated, so the initWithStyle:reuseIdentifier method from Objective-C is named style:reuseIdentifier in Swift.

Build an Run the project, you will see a Table View with the rows filled.

You can download the source code of the iOS8SwiftTableViewTutorial at the ioscreator repository on github.