Mobile Development

Welcome to Swift

Hello and welcome to Swift, Apple's programming language designed to for creating iOS and Mac applications.

Swift is a new programming language developed by Apple for the development of iOS and OSX applications. Like many other high-level languages, Swift facilitates the creation of complex objects and modern programming patterns. This is different from the C-based paradigm of Swift's predecessor, Objective-C. Swift also aims reduce overall amounts of code from Objective-C by providing a more succinct language and file structure.

Swift was introduced by Apple at the WWDC 2014 event.

[Video] Introduction to Swift

The following gives a great overview of the language of Swift and why developers should use it: Introduction to Swift

The Basics

Below, we will list a few basics of the Swift programming language. These examples can be pasted into a Playgrounds window and changed there. By using Playgrounds, you will be able to ensure the code compiles, runs and see the output of each line in real-time.

Declaring a variable

Variables represent data within a Swift application:

let staticVariable = "This won't ever change"
var dynamicVariable = "This can change"

dynamicVariable = "... you've changed!"

Optionals

In Swift, you can define a variable that may be uninitialized (or nil) by using the "?" operator.

var newClientName: String? 
// newClientName is initialized as nil

If you know that an optional variable is currently not nil, you can force unwrapping by using the "!" operator

var newClientName: String?
newClientName = "Apple"
let client = newClientName!

Performing arithmetic

You can then use variables to perform actions, like math. Swift defines a variety of operations for mathmatical computation including:

  • =   Equals
  • +   Addition
  • -   Subtraction
  • /   Division
  • *   Multiplication
  • %   Remainder
  • ++   Increment
  • --   Decrement
let a = 1
let b = 2
var c = a + b
print(c) // prints 3

var d = c + a
print(d) // prints 4

For more examples on mathmatical operations, please visit: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html

Control flows

There are a variety of control flows you can use to iterate over data and repeat a particular set of instructions.

These examples were adapted from Apple's Swift documentation [1].

For-in

The For-In loop will repeat its control block until the condition is met.

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    println("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!

For

Swift also supports the more traditional For control loop.

// Format
for initialization; condition; increment {
    statements
}

Refactoring our last example, we can come up with the same result.

let names = ["Anna", "Alex", "Brian", "Jack"]

// initial; continue until; 
for var index = 0; index < names.count; ++index {
    println("name at index \(index) is \(names[index])")
}
// name at index 0 is Anna
// name at index 1 is Alex
// name at index 2 is Brian
// name at index 3 is Jack

While

Another type of control is the while loop. This loop will continue until the condition is met. Special care should be taken to avoid running an infinite loop.

while condition {
    statements
}

For example:

var counter = 1
while counter <= 5 {
    println("we've counted to \(counter)")
    counter++
}
//we've counted to 1
//we've counted to 2
//we've counted to 3
//we've counted to 4
//we've counted to 5

Conditionals

Swift provides a standard set of conditional statements that can be used for checking states of variables and performing optional chains of events.

If Else

The most common conditional statement is evaluating a variable for a particular condition. For example:

var composerType: String?

if composer == "Bach" {
    composerType = "Baroque"
}
else if composer == "Beethoven" {
    composerType = "Classical"
}
else if composer == "Schumann" {
    composerType = "Romantic"
}
else { // if the above conditions are not met, the execution will come here
    composerType = "Uknknown"
}

print("\(composer) is \(composerType)")
// Beethoven is Classical

Switches

A switch statement considers a value and compares it against several possible matching patterns [1]

The patterns in this case can be a single value, multiple values and ranges of values.

switch value to consider {
case value 1:
    respond to value 1
case value 2,
     value 3:
    respond to value 2 or 3
default:
    otherwise, do something else
}

As we fill out our example below based on the above format, we are also introducing the range operator (...) which is a quick way to include a range of values from x to y.

let breakfastCost = 10

switch breakfastCost {
case 0:
    print("Free?!  I'll take it!")
case 1...4:
    print("Sounds good.  I'll buy it!")
case 5...7:
    print("Grumble.  I guess.")
case 8...10:
    print("I'm going elsewhere")
default:
    print("Highway robbery!")
}

Storage

Swift provides a variety of storage types (aka variables). Let's go over some of them now.

Swift types

We have already used quite a few of these up to this point.

let likeCats: Bool = true
let numberOfCatsOwned: Int = 25
let dollarsCatsCostMe: Double = Double(numberOfCatsOwned) * 500.0
let name: String = "Batman"

The second to last example casts (converts) the numberOfCatsOwned which was an Int to a Double with the syntax Double(Int).

Tuples

Tuples are a group of two or more variables coupled together. They can be different types. Tuples provide a convenient way of passing around a set of information in code.

let balloon = (12.0, "Red")

let (diameter, color) = balloon
println("The balloon diameter is \(diameter)")
println("The balloon color is \(color)")

// Output
// The balloon diameter is 12.0
// The balloon color is Red

Arrays

An array stores multiple values of the same type in an ordered list. [1]

Arrays are useful for storing and enumerating collections of similar types.

var lbNeighborhoods = ["Downtown", "Bixby Knolls", "North Long Beach", "Wilmore", "California Heights", "Cambodia Town", "Belmont Shore", "Naples Island", "Retro Row"];

for hood in lbNeighborhoods {
    if hood == "North Long Beach" {
        println("\(hood) is home!")
    }
    else {
        println(hood)
    }
}

// Create a new, blank array which will contain Strings
var placesLived = Array<String>()

// Add some data
placesLived.append("Downtown")
placesLived.append("North Long Beach")

Dictionaries

Dictionaries are a set of key-value pairs. Each key must be unique.

var contacts = ["Jeff" : "201-555-5555", "Joe" : "212-555-6666", "Sarah" : "917-555-7777", "Obama" : "202-555-8888"]

var obamaPhone = contacts["Obama"]
print(obamaPhone)
// 202-555-8888

Defining a function

Organize actions into functions:

func exampleFunction(thisIsFun:Bool) -> String {

    var returnValue = "No, this isn't fun."
    if thisIsFun {
        returnValue = "Yes, this is fun!"
    }

    return returnValue
}

let enjoyment = exampleFunction(true)
print("Is Swift fun? \(enjoyment)")

These are some of the basic tenants of the Swift programming language. As we move the course, you will experience more of the Swift programming language expanding your knowledge and repertoire.

References

[1] Swift Programming Language https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language

Swift Resources https://developer.apple.com/swift/resources/

Style Guide Reference https://github.com/github/swift-style-guide

Trending Swift Repositories on GitHub https://github.com/trending?l=swift&since=monthly