Swiftly Learning Swift !

Its June 2014. Half of the world is going crazy with FIFA World Cup happening in Brazil & the other half is going crazy over the new programming language, Swift, introduced by Apple in WWDC 2014.

How about we unite them here ? 😉 I am as much excited as you are in adopting Swift in my iOS applications. In this simple tutorial lets create an application which will list all the countries participating in FIFA World Cup 2014. Tapping on a specific country will display their country flag in a detail view – Everything in SWIFT !

Prerequisites

  • Xcode 6
  • Knowledge on Objective C programming using storyboard
  • Basic knowledge on swift (like variables, functions,etc)

Lets get started by creating a new project as shown below

FIFASwift01

Notice that we don’t have any header files that we used to get in iOS apps using Objective C. Another thing to note is we have a common storyboard for both iPhone & iPad . We will make this application for only for iPhone. As an exercise, you can create the same for iPad.

Lets add a navigation controller to our view controller

Editor -> Embed In -> Navigation Controller

Add a Search Bar & Table View in the view controller and add auto layout constraints (You can learn more about auto layouts here)

FIFASwift02

 

Drag and drop a TableView Cell and set the cell identifier as FifaTeamCell. We will be using this identifier to reuse the table view cells in our table

FIFASwift04

 

Lets create IBOutlets by wiring Search Bar & Table View using Assistant Editor . Set the delegates of Search Bar & Table View to the ViewController

FIFASwift03

Create variables to store names of the teams, the matching strings during search operation & the index of the selected team as given below


var fifaTeams: String[] = []

var searchResultsOfFifaTeams: String[] = []

var indexOfSelectedTeam = 0

Lets initialise fifaTeams with the names of the teams.

//Initialise team names


fifaTeams = ["Brazil", "Croatia", "Mexico", "Cameroon", "Spain", "Netherlands", "Chile", "Australia","Columbia", "Greece", "Côte d'Ivoire", "Japan", "Uruguay", "Costa Rica", "England", "Italy","Switzerland", "Ecuador", "France", "Honduras", "Argentina", "Bosnia-Herzegovia", "Iran","Nigeria","Germany", "Portugal", "Ghana", "USA", "Belgium", "Algeria", "Russia", "Korea"]

//Search array is same as our original team array. It will change based on the search strings

searchResultsOfFifaTeams = fifaTeams

Now, we fill the table with the names of the teams declared in searchResultsOfFifaTeams variable


//UITableView DataSource & Delegate methods

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int

{

return searchResultsOfFifaTeams.count

}

func numberOfSectionsInTableView(tableView: UITableView!) -> Int

{

return 1;

}

func tableView(tableView: UITableView!,

cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!

{

var tableCell = tableView.dequeueReusableCellWithIdentifier("FifaTeamCell", forIndexPath: indexPath) as UITableViewCell!

tableCell.textLabel.text = searchResultsOfFifaTeams[indexPath.row]

tableCell.textLabel.textColor = UIColor.blackColor()

return tableCell;

}

If you run the program on iPhone simulator, you will see a list of teams which we initialised earlier. Now, we will add search functionality to this list.

Before we jump into the implementation, I would like to talk about playground feature introduced in Xcode 6. Its allows you to create prototype implementation, work on logic before you integrate it with your main app. To have a glimpse on the playground, lets prototype our search functionality using playground.

Create a new playground file as shown below

FIFASwift05

Lets write a logic to search the teams in the list based on the search string. FIFASwift06

As you can see, we were able to see the results even before we integrate this snippet of code in our application. Thank you Apple for introducing “Playground” !

We will implement rest of the search bar delegates as shown below


func searchBarShouldBeginEditing(searchBar: UISearchBar!) -> Bool // return NO to not become first responder

{

return true

}

func searchBarTextDidBeginEditing(searchBar: UISearchBar!) // called when text starts editing

{

}

func searchBarShouldEndEditing(searchBar: UISearchBar!) -> Bool // return NO to not resign first responder

{

return true

}

func searchBar(searchBar: UISearchBar!, textDidChange searchText: String!) // called when text changes (including clear)

{

//Remove all objects first.

searchResultsOfFifaTeams.removeAll(keepCapacity: true)

if(!searchText.isEmpty) {

//If search string is available, search for matching team & add it in searchResultsOfFifaTeams

searchTeamName(searchText)

}else

{

//If search string is not available, initialise it back to fifaTeams

searchResultsOfFifaTeams = fifaTeams

}

//reload the table

countryNameTableView.reloadData()

}

func searchTeamName(searchText: String){

for teamName in fifaTeams

{

if teamName.bridgeToObjectiveC().localizedCaseInsensitiveContainsString(searchText)

{

searchResultsOfFifaTeams.append(teamName)

}

}

}

 

If we build and run the app on iPhone simulator, we will be able to see the list of team names and search our favourite team !

Lets add another view controller and add a segue ID as “DetailsViewID”. Lets create ImageView and UILabel as IBOutlets in the DetailsViewController. Add a member in DetailsViewController to hold the value of selected team name


var selectedTeamName:String?

FIFASwift07

The infrastructure that we need for the DetailsViewController is ready. We just need to pass the selected team name to the DetailsView and display the team flag & a message.


override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)

{

if segue.identifier == "DetailsViewID"

{

let detailsViewController = segue.destinationViewController as DetailsViewController

println("Selected country name - \(searchResultsOfFifaTeams[indexOfSelectedTeam])")

let selectedName:NSString = searchResultsOfFifaTeams[indexOfSelectedTeam]

}

}

 

Even though swift is safe, one thing to note here is if we are working with Foundation class objects, special care must be taken. To illustrate this, lets try to assign the text of label which we created in DetailsViewController with the team name which the user selects in the list


detailsViewController.messagelabel.text = "Brazil"

If you run this code on the simulator & select a team name in the list, the application crashes with the message

fatal error: Can’t unwrap Optional.None

This means that we are trying to access the object which doesn’t exist. Remember we created this label in the IB & it will not be available till the segue completes its transition.

In the DetailsViewController, write this method which will set the image view with the flag of the selected team.


func  setImagForSelectedTeam()

{

teamFlagImageView.image = UIImage(named:selectedTeamName)

}

Now, if you run the application, you can see the flag of the selected team.

FIFASwift08 FIFASwift09

 

You can download the source code from this link.

Even though its a very simple tutorial, it allows you to explore options to implement swift in your iOS applications.

Cheers to Swift ! 🙂