Collections in Swift

Swift offers a wide range of classes for managing collections. Above all, Swift benefits from dictionaries and arrays.

Collections in Swift: Dictionaries

Dictionaries in Swift are rather simplified and powerful. We declare dictionaries by a var or let of the type dictionary and then we can explicitly mention the type of the values in that dictionary. Firstly, we could also let the types be inferred from the values. Secondly, once we have a dictionary, we can add new key-value pairs to it or update them.

Dictionaries in Swift

Tuples

For iterating within a dictionary, we rely on tuples. Tuples are a powerful ordered set of values. The values can be accessed by index or by name. As a result of this powerful ability, many Swift objects use tuples to access their inner properties and values.

// Tuples in Swift 

var person = ("John", "Smith")
var firstName = person.0 // John

var lastName = person.1 // Smith

var person2 = (firstName: "John", lastName: "Smith")
var firstName = person2.firstName // Johnvar 
lastName = person.1 // Smithvar 

namesOfIntegers = [Int: String]()
namesOfIntegers[16] = "sixteen"

Collections in Swift: Arrays

Arrays in swift are rather simplified as opposed to Objective-C. Above all, you can declare and define arrays similar to C by simply adding the objects into the array.

Arrays in Swift

In addition, arrays can be implicitly defined. As a result, you can use arrays such as the following. That is to say that the array type infers from its content.

// Swift Arrays

var myArray = ["Hello", "World", "Swift", "iOS"]
print ("\(myArray)") // "Hello", "World", "Swift", "iOS"

myArray.remove(at: 1)

print ("\(myArray)") // "Hello", "Swift", "iOS"

myArray.append("ObjC")

print ("\(myArray)") // "Hello", "World", "Swift", "iOS", "ObjC"

However, you could also explicitly define the type of the objects in an array such as String in the following example:

// Arrays with explicit type

var myArray : Array <String> = ["Hello", "World", "Swift", "iOS"]
if let index = myArray.index(of: "Hello") 
{
    print("Found Hello at index \(index)")
}

Moreover, you can use Any for arras where the type is not predetermined

Moreover, you can still use the NSArray if you prefer, but you cannot explicitly select its type. Instead, the array will infer its type from the content added to it.

// NSArrays in Swift 

var myNsArr : NSMutableArray = NSMutableArray.init(objects: "Hi", "World");
myNsArr.index(of: "Hi") // 0

Interested in learning more in-depth concepts?

If you are interested in learning more about mobile app development, I invite you to join my complete iPhone or Android course(s):

Leave a Comment