Channels ▼
RSS

Mobile

Swift: Introduction to Apple's New Programming Language


Apple began accepting Swift-coded applications in the App Store after the launch of both iPhone 6 and iPhone 6 Plus. In this article, I provide a brief introduction of the most interesting features included in this new programming language, which provides an alternative to Objective-C when you want to create native iOS apps with XCode 6.0.x.

A New Language, A New XCode Version

Swift is an object-oriented language that includes some functional programming concepts. I believe the most important benefit that Swift provides is that you can avoid working with Objective-C to develop a native iOS app. However, you still have to work with XCode, as it is the only IDE that allows you to work with Swift to develop iOS apps. Luckily, XCode 6.0.1 solved many of the bugs related to Swift that made it almost impossible to complete a working session without unexpected errors and crashes in the beta versions of the IDE that supported Swift. There are still many bugs that would require an update to get solved, but I was able to use XCode and the iOS emulator while working on complex apps without major problems for many days. You can install XCode 6.0.1 from the Mac App Store. I don't recommend you work with earlier XCode versions that included support for Swift because they are very unstable.

If you have some experience with C#, Java, Python, Ruby, or JavaScript, you will find Swift's syntax easy to learn. You may still miss many advanced features included in those programming languages that aren't available in Swift, but you will benefit from the features that Swift did borrow from these and other modern programming languages. Swift doesn't require the use of header files. You can import any Objective-C module and C libraries to Swift with simple import statements.

XCode 6.0.1 offers a Swift interactive Playground that allows you to write Swift lines of code and check the results immediately. This Playground is really helpful for learning Swift and its interaction with the APIs because it provides nice code completion features. You simply need to start XCode, select File | New | Playground…, enter a name for the Playground, select iOS as the desired platform, click Next, select the desired location for the Playground file, and click Create. XCode will display a Playground window with the following lines of code:

// Playground - noun: a place where people can play

import UIKit

var str = "Hello, playground"

You can add your Swift lines of code and check the results as you enter them in the right hand side of the window. In fact, you can use the Playground to test the sample lines of code I will provide (see Figure 1).

Swift
Figure 1: Checking the results of Swift code in the Playground.

Type Inference, Variables, and Constants

Swift doesn't require you to write semicolons at the end of every statement. The type inference mechanism determines the best type, and you can avoid specifying the type of value. You can declare constants with the let keyword. and variables with var. For example, the following line creates an immutable String named welcomeText.

let welcomeText = "Welcome to my Swift App"

The following line uses the var keyword to create a highScore Int mutable variable.

var highScore = 5000

One nice feature is that you can use underscore (_) as a number separator to make numbers easier to read within the code. For example, the following lines assign 3000000 and 5000 to the previously declared highScore variable:

highScore = 3_000_000
highScore = 5_000

You can explicitly specify the desired type for a variable. The following line creates a scoreAverage Double mutable variable. In this case, the type inference mechanism would choose Int as the best type because the initial value is 100. However, I want a Double to support future values, so I specify the type name in the variable declaration.

var scoreAverage: Double = 100

Swift makes it simple to include values in strings. You just need to use a backslash (\) and include an expression within parenthesis. For example, the following line:

var highScoreText = "The highest score so far is: \(highScore)"

Stores the following string in highScoreText:

"The highest score so far is: 5000"

The following line includes a more complex expression that doubles the value of highScore:

var doubleHighScoreText = "Are you ready to reach this score: \(highScore * 2)"

The line stores the following string in doubleHighScoreText:

"Are you ready to reach this score: 10000"

You can declare an optional value by adding a question mark after the type. The following lines declare the optionalText variable as an optional String. The initial value is nil and indicates that the value is missing. The next lines use if combined with let to retrieve the value in an operation known as optional binding. In the first case, the value is nil and the println line doesn't execute. Notice that nil means the absence of a value (and don't confuse it with the usage of nil in Objective-C). After the line that assigns a value to optionalText executes, the next if combined with let retrieves the value in text and prints an output with the retrieved String. Notice that the Boolean expression for the if statement doesn't use parenthesis because they are optional. However, braces around the body are always required even when the statement is just one line.

var optionalText: String?
if let text = optionalText {
    println("Optional text \(text)")
}

optionalText = "You must work harder to increase the score!"
if let text = optionalText {
    println("Optional text \(text)")
}

Generic Classes and Functions

Swift allows you to make generic forms of classes. The following lines show a simple example of a Point3D class that specifies T inside angle brackets to make a generic class with three variables: x, y, and z and a method that returns a String description. You can also use generics with functions, methods, enumerations, and structures.

class Point3D<T> {
    var x: T
    var y: T
    var z: T
    
    init(x: T, y: T, z: T) {
        self.x = x
        self.y = y
        self.z = z
    }
    
    func description() -> String {
        return "Point.X: \(self.x); Point.Y: \(self.y); Point.Z: \(self.z)."
    }
}

The initializer (init) sets up the class when you create an instance. In this case, the initializer assigns the values received as three arguments for x, y, and z. The arguments use the same name as the class variables, so it is necessary to use self to distinguish the x, y, and z properties from the arguments. If you need to add some cleanup code before the instance is deallocated, you can put some code in deinit.

The following lines create an instance of a Point3D with Int values and another Point3D with Double values. Then, two lines print the result of calling the description method for each Point3D instance.

var pointInt = Point3D<Int>(x: 10, y: 5, z: 5)
println(pointInt.description())
var pointDouble = Point3D<Double>(x: 15.5, y: 5.5, z: 32.5)
println(pointDouble.description())

I'll use a Point3D<Int> instance to clarify the use of the let keyword with instances. The following line declares pointIntConst as a constant.

let pointIntConst = Point3D<Int>(x: 5, y: 5, z: 5)

Thus, you cannot change the value for pointIntConst; that is, you cannot assign a different instance of Point3D<Int> to it. However, you can change the values for the instance properties. For example, the following line is valid and changes the value of x.

pointIntConst.x = 3

As happens in many modern programming languages, functions are first class citizens in Swift. You can use functions as arguments for other functions or methods. The following lines declare the applyFunction function that receives an array of Int (list) and a function (condition) that receives an Int and returns a Bool value. The function executes the received function (condition) for each element in the input array and adds the element to an output array whenever the result of the called function is true. This way, only the elements that meet the specified condition are going to appear in the resulting array of Int.

func applyFunction(list: [Int], condition: Int -> Bool) -> [Int] {
    var returnList = [Int]()
    for item in list {
        if condition(item) {
            returnList.append(item)
        }
    }
    
    return returnList
}


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video