Codementor Events

Getting Started with Swift

Published Sep 20, 2016Last updated Jan 18, 2017
Getting Started with Swift

Why Swift?

Swift is quickly becoming the programming language of choice for native iOS applications because of its more intuitive and concise syntax as compared to Objective-C. Swift is also becoming its own universal language outright with an independent implementation under active development at swift.org and from other providers like IBM.

This tutorial is designed to put you on the fast train for Swift development assuming you have familiarity with another major language such as JavaScript, Java, or Objective-C.

Hello World!

Here is a traditional hello world program in Swift. You can follow along yourself by coding Swift in your browser with iSwift's browser playground.

let x = "Hello World!"
print(x)

There are a couple things we notice right away from this example. First of all, there are no semicolons. No end of statement character is needed in Swift. However, every statement must be on its own line — otherwise, a semicolon is needed! For instance, the following also works.

let x = "Hello World!"; print(x)

Another observation we make is the let keyword. In Swift, constants are defined with let and variables are defined with var. Finally, the print function in Swift is notable with its single string argument. There is also printf which will be familiar to C developers and println which is a hallmark of Java.

Literals & Typing

Swift is a type-safe language, but unlike Objective-C, the Swift compiler is extremely adept at guessing the correct type. Because of this, we rarely need to define a type. The following example shows variable assignments where the data type is automatically determined.

var snack = "Almond"
let four = 0b100, one = 1.0, half = 0.5

In the example above, snack is automatically determined to be of type String, four is assumed to be an Int, and both one and half are typed as Double.

There are some occasions where a type must be provided and this is done with a Type Annotation. Below is how we specify a Character data type in Swift.

let amp : Character = "&"

The : Character Type Annotation instructs the Swift compiler that amp is of type Character — otherwise it would be assumed to be a String.

Functions

The function syntax in Swift is unique, but quite intuitive. Let's have a look:

func outputPlanet(isEarth : Bool) -> String {
  let e = "Earth", v = "Venus"
  var result : String
  if isEarth {
    result = e
  } else {
    result = v
  }
  return result
}

Notice the function signature. If the function returns something, Swift requires that type to be defined with -> Type. If a function does not return anything, that part is omitted. For example, the following function does not have a return type.

func printPlanet(isEarth : Bool) {
  let e = "Earth", v = "Venus"
  var result : String
  if isEarth {
    result = e
  } else {
    result = v
  }
  print(result)
}

Now let's look at how these functions would be called.

let str = outputPlanet(isEarth : true)
printPlanet(isEarth : false)

Notice the arguments include a parameter name of isEarth : which is optional. However, if a function has more than one parameter, they become required beginning with the second parameter. For example, take a look at the function with two parameters below.

func decorateString(str : String, decor : Character) -> String {
  return "\(decor)\(decor) \(str) \(decor)\(decor)"
}

let tilda : Character = "~"
let cutsie = decorateString("prettyme", decor : tilda)
// cutsie is: ~~ prettyme ~~

Optionals

Optionals are a special type in Swift and they are probably the most confusing aspect of the language for someone new. An Optional is essentially a container object that may be empty. The Swift language designers created the Optional type to abstract the programmer from pointers and references.

They can take some getting used to, but there isn't that much to learn. Let's take a look at creating an Optional.

var id : Int?

Make no mistake, id is not an Int type. Instead, it is of Optional type which could contain an Int or could be empty.

All types can be defined as Optionals and when used need to be tested to ensure they are not empty and "unwrapped" to access their containing value. For example, the following code tests that id is non-empty and then prints the containing value.

if id != nil {
  let trueId = id!
  print(trueId)
}

So what is going on here? Well, first id is checked to be non-empty by comparison to nil. Then, we get its containing value with the ! symbol. We could just use print(id!) but unless we are certain id will always be populated, a Swift program crashes if an Optional is unwrapped when it is empty!

Apple and iOS APIs make use of the Optional type frequently so sooner or later, this is likely to be something a Swift developer needs to get their head around.

Collections

The primary collection data structures in Swift are Array, Set, and Dictionary.

The following example creates an array of strings and appends a new element.

var arr : [String] = ["Pine", "Oak", "Juniper"];
arr.append("Mahogany")

Below is an example that creates a Dictionary and removes an item.

var dict : [String: UInt] = ["red": 0xFF0000, "green": 0x00FF00, "blue": 0x0000FF]
dict.removeValueForKey("red")

Iteration

Ah yes, we must loop! Swift supports dated C-style iteration as follows.

let arr : [Int] = [1, 2, 3, 4];
for var i=0; i<arr.count; i++ {
  print(arr[i])
}

A more modern approach is to use for...in syntax as shown below.

let arr : [Int] = [1, 2, 3, 4];
for i in arr {
  print(i)
}

The other loops supported by Swift are while and repeat-while which is known as do-while in other languages.

Classes

Creating a class in Swift will come easily if there is familiarity with object-oriented programming. Below is a simple class that has a couple instance variables, an Initializer, and a method — we call it a method instead of a function because it is a member of a class.

class Person {
  var first : String, last : String
    
  init(first : String, last : String) {
    self.first = first
    self.last = last
  }
    
  func printSelf() {
    print("My name is: \(first) \(last)")
  }
}

Notice init which is called an Initializer. This is equivalent to a constructor in other languages. Below is an example of creating an instance of Person and calling the printSelf() method.

let p = Person(first: "Siddhartha", last: "Maitreya")
p.printSelf()

Conclusion

With this crash course of sorts, you will know enough to be dangerous in Swift. Should more information be needed, in my opinion, there is no better resource than the official Swift Language Guide from Apple.

Discover and read more posts from Lightbeard
get started
post comments1Reply
shoopwhoop
8 years ago

I’d like to mention that it’s tilde, not tilda. But other than that – great beginner guide.