IOS

Basic Data Types in Swift

The 5 data types in Swift and their basic uses:

Strings

let constantString = "Hi"
var x = constantString + " you."
var x = "\(constantString) you."
// If you want to use double quote in Strings, use \"

Arrays (first of three Collection Types)

var arr = [1, 2, 3]        // [1, 2, 3]
arr[0] = 0                 // [0, 2, 3]
arr += [4, 5]              // [0, 2, 3, 4, 5]
arr.removeAtIndex(1)       // returns the element removed, in this case 2, which leaves the arr at [0, 3, 4, 5]
arr.count                  // 4

for num in arr {
    // Arrays are ordered collections
}

Dictionaries (second of three Collection Types)

var dictionary = ["one": 1, "two": 2, "three": 3]
let value = dictionary["two”]
dictionary[“four”] = 4       // dictionary is now ["one": 1, "two": 2, "three": 3, "four": 4]
dictionary["three"] = nil    // dictionary is now ["one": 1, "two": 2, "four": 4]
dictionary.removeAll()       // dictionary is now an empty dictionary

for (key, value) in dictionary {
    // Dictionaries are unordered collections.
    // Although it looks like an array, there’s no 
    // guarantee that the iteration will go according to it
}

Sets (last of three Collection Types)

This is a new “unordered collection of distinct objects” type in Swift, as of Swift 1.2. Basic methods of Sets include:

var foodSet = Set(["Apple", "Pie"])
foodSet.contains("Sandwiches")
foodSet.insert("Salad")
foodSet.remove("Chips")
foodSet.removeAll()
foodSet.count
foodSet.isEmpty
entreeSet.isSubsetOf(foodSet)
foodSet.isSupersetOf(entreeSet)
foodSet.union(otherFoods)
otherFoods.subtract(entreeSet)
moreFoods.intersect(entreeSet)

Numeric Types

// 1. Integer Types: 
let a = 42      // is of type Int

// 2. Floating Point Types:
let b = 42.0    // is of type Double

// 3. Boolean Type:
var c = false   // is of type Bool

 

Read more about them here [Swift Standard Library Reference] and here [Swift Set Type in Swift 1.2].

Standard