Data Types in Swift

I’m currently teaching a mobile development course at GA. I’ll be sharing my swift lessons one by one. Lesson 1: Data Types.After reading this blog post you’ll be able to learn and use the basic data types in Swift.I’m going to briefly introduce a data type. Then I’ll show the syntax for creating it and what you can do with it.

Ready, get set, go!


The String datatype is used for storing and manipulating text. You start defining a string by using a double quotes symbol following by your text. Finish defining your string by using a second double quotes symbol.

""                    // an empty string
"hello world"         // a string with words

countElements("dude") // => 4
"dude".isEmpty        // => false
"".isEmpty            // => true


A boolean can be either true or false. It’s useful in conditions inside control flow statements like if. It also helps with checking whether a certain condition is met.

true  // a boolean with a value of true
false // a boolean with a value offalse

let age = 19
if age >= 18 {
  println("Congratulations! Now you can now get a California driver license.")


The Range data type is used to define a range of values. It’s very handy to define long sequences.

0...3 // => 0,1,2,3
0..<3 // => 0,1,2</pre>


An integer describes a whole number without a decimal point. It’s useful for performing any sort of math on whole numbers.

1     // an integer with a value of 1

1 - 2 // => -1
3 + 2 // => 5
2 * 2 // => 4

Double / Float

Doubles and Floats are used for numbers with precision. A double is twice as precise as a float.

4.2 // a double with a value of 4.2

let my_float : Float = 4.2 // If you want to use float to consume some memory, you'll need to explicitly specify avariable'stype</pre>


Array is a zero indexed, ordered collection of elements.Arrays come in handy when you need to store and operate on a collection of elements.

["a","b","c","d"]    // an array of characters
[1.2, 3.4, 6.7, 5.6] // an array of numbers

[1,2] + [2,4]        // => [1,2,3,4]
let my_array = [1,2,3,4]
my_array.count       // => 4

// retrieving the first element of an array
my_array[0]          // => 1


A dictionary is a collection of key value pairs. A value is stored and retrieved from a dictionary by it’s key. Dictionaries are useful for managing different sets of data. For example keeping a track of heroes and their superpowers 😉

// A dictionary with 3 key value pairs
var heroes = [
 "wonder_woman": ["strong"],
 "aqua_man": ["can breathe underwater"],
 "wonder twins": ["take forms of other things"]

// retrieving values using keys
heroes["wonder_woman"] // => strong
heroes["aqua_man"]     // => can breathe underwater

// inserting a new key / value pair
heroes["spiderman"] = ["spidey sense", "throw a web"]</pre>

Feel free to play with this code in the playgrounds. Every data type has a lot more useful methods on it.



Photo by yukop