Immutable/Mutable Collections in Swift

Pranav Jaiswal picture Pranav Jaiswal · Jun 7, 2014 · Viewed 83.4k times · Source

I was referring to Apple's Swift programming guide for understanding creation of Mutable/ immutable objects(Array, Dictionary, Sets, Data) in Swift language. But I could't understand how to create a immutable collections in Swift.

I would like to see the equivalents in Swift for the following in Objective-C

Immutable Array

NSArray *imArray = [[NSArray alloc]initWithObjects:@"First",@"Second",@"Third",nil];

Mutable Array

NSMutableArray *mArray = [[NSMutableArray alloc]initWithObjects:@"First",@"Second",@"Third",nil];
[mArray addObject:@"Fourth"];

Immutable Dictionary

NSDictionary *imDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"Value1", @"Key1", @"Value2", @"Key2", nil];

Mutable Dictionary

NSMutableDictionary *mDictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Value1", @"Key1", @"Value2", @"Key2", nil];
[mDictionary setObject:@"Value3" forKey:@"Key3"];

Answer

nicael picture nicael · Jun 7, 2014

Arrays

Create immutable array

First way:

let array = NSArray(array: ["First","Second","Third"])

Second way:

let array = ["First","Second","Third"]

Create mutable array

var array = ["First","Second","Third"]

Append object to array

array.append("Forth")


Dictionaries

Create immutable dictionary

let dictionary = ["Item 1": "description", "Item 2": "description"]

Create mutable dictionary

var dictionary = ["Item 1": "description", "Item 2": "description"]

Append new pair to dictionary

dictionary["Item 3"] = "description"

More information on Apple Developer