Pranav Jaiswal Pranav Jaiswal - 1 year ago 138
Objective-C Question

Immutable/Mutable Collections in Swift

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 Source


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



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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download