Swift中的不可变/可变集合 [英] Immutable/Mutable Collections in Swift

查看:121
本文介绍了Swift中的不可变/可变集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指的是Apple的Swift编程指南,用于理解用Swift语言创建Mutable / immutable对象(Array,Dictionary,Sets,Data)。但我无法理解如何在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.

我想在Objective-C中看到Swift中的等价物

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

不可变数组

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"];


推荐答案

数组



创建不可变数组

第一种方式:

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开发人员的更多信息

这篇关于Swift中的不可变/可变集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆