一尘不染

Swift中的不可变/可变集合

swift

我指的是Apple的Swift编程指南,以了解如何用Swift语言创建可变/不可变对象(数组,字典,集合,数据)。但是我不明白如何在Swift中创建一个不可变的集合。

我希望在Objective-C中看到以下Swift中的等效项

不变数组

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

可变数组

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

不变字典

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

可变字典

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

阅读 278

收藏
2020-07-07

共1个答案

一尘不染

数组

创建不可变数组

第一种方式:

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

第二种方式:

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

创建可变数组

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

将对象追加到数组

array.append("Forth")

辞典

创建不可变字典

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

创建可变字典

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

将新的配对添加到字典

dictionary["Item 3"] = "description"

有关Apple
Developer的更多信息

2020-07-07