ios Swift 中的不可变/可变集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24096096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:38:11  来源:igfitidea点击:

Immutable/Mutable Collections in Swift

iosobjective-cswiftimmutabilitymutable

提问by Pranav Jaiswal

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.

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

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

我想在 Swift 中看到 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"];

回答by nicael

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

有关 Apple 开发人员的更多信息

回答by Abhi Beckert

Swift does not have any drop in replacement for NSArrayor the other collection classes in Objective-C.

Swift 没有任何替换NSArray或替换Objective-C 中的其他集合类。

There are array and dictionary classes, but it should be noted these are "value" types, compared to NSArray and NSDictionary which are "object" types.

有数组和字典类,但应该注意的是,与作为“对象”类型的 NSArray 和 NSDictionary 相比,这些是“值”类型。

The difference is subtle but can be very important to avoid edge case bugs.

差异很微妙,但对于避免边缘情况错误非常重要。

In swift, you create an "immutable" array with:

在 swift 中,您创建一个“不可变”数组:

let hello = ["a", "b", "c"]

And a "mutable" array with:

和一个“可变”数组:

var hello = ["a", "b", "c"]

Mutable arrays can be modified just like NSMutableArray:

可变数组可以像这样修改NSMutableArray

var myArray = ["a", "b", "c"]

myArray.append("d") // ["a", "b", "c", "d"]

However you can't pass a mutable array to a function:

但是,您不能将可变数组传递给函数:

var myArray = ["a", "b", "c"]

func addToArray(myArray: [String]) {
  myArray.append("d") // compile error
}

But the above code does work with an NSMutableArray:

但是上面的代码确实适用于 NSMutableArray:

var myArray = ["a", "b", "c"] as NSMutableArray

func addToArray(myArray: NSMutableArray) {
  myArray.addObject("d")
}

addToArray(myArray)

myArray // ["a", "b", "c", "d"]

You can achieve NSMutableArray's behaviour by using an inoutmethod parameter:

您可以NSMutableArray通过使用inout方法参数来实现的行为:

var myArray = ["a", "b", "c"]

func addToArray(inout myArray: [String]) {
  myArray.append("d")
}

addToArray(&myArray)

myArray // ["a", "b", "c", "d"]

Re-wrote this answer 2015-08-10 to reflect the current Swift behaviour.

2015 年 8 月 10 日重新编写了此答案以反映当前的 Swift 行为。

回答by ColinE

There is only one Arrayand one Dictionarytype in Swift. The mutability depends on how you construct it:

只有一个Array和一个Dictionary类型的斯威夫特。可变性取决于您如何构建它:

var mutableArray = [1,2,3]
let immutableArray = [1,2,3]

i.e. if you create an assign to a variable it is mutable, whereas if you create an assign to constant it is not.

即如果你创建一个赋值给一个变量它是可变的,而如果你创建一个赋值给常量它不是。

WARNING:Immutable arrays are not entirely immutable! You can still change their contents, just not their overall length!

警告:不可变数组并非完全不可变!您仍然可以更改它们的内容,只是不能更改它们的总长度!

回答by iPatel

Just declare your (any)object or variable with

只需声明您的(任何)对象或变量

'let' key word -> for "constan/Immutable" array, dictionary, variable, object..etc.

and

'var' key word -> for "Mutable" array, dictionary, variable, object..etc. 

For more deeply information

如需更深入的信息

“Use letto make a constant and varto make a variable. The value of a constant doesn't need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places."

“使用let生成常量,使用var生成变量。编译时不需要知道常量的值,但必须只为其赋值一次。这意味着您可以使用常量来命名一个您确定一次但在许多地方使用的值。”

var myVariable = 42
myVariable = 50
let myConstant = 42

Read “The Swift Programming Language.”

阅读“Swift 编程语言”。

回答by Moti F.

If you want to work with Array(Swift) as with NSArray, you can use a simple bridge function. Example:

如果你想像 with 一样使用Array(Swift) NSArray,你可以使用一个简单的桥接函数。例子:

var arr1 : Array = []

arr1.bridgeToObjectiveC().count

It works the same for let.

它对let.

回答by Balthazar

From Apple's own docs:

来自苹果自己的文档:

Mutability of Collections

If you create an array, a set, or a dictionary and assign it to a variable, the collection that is created will be mutable. This means that you can change (or mutate) the collection after it is created by adding, removing, or changing items in the collection. Conversely, if you assign an array, a set, or a dictionary to a constant, that collection is immutable, and its size and contents cannot be changed.

集合的可变性

如果创建数组、集合或字典并将其分配给变量,则创建的集合将是可变的。这意味着您可以在创建集合后通过添加、删除或更改集合中的项目来更改(或变异)集合。相反,如果将数组、集合或字典分配给常量,则该集合是不可变的,并且其大小和内容不能更改。

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105

Other uses of immutable/mutable collections depend on why you want them to be mutable/immutable. Collections are valuetypes in Swift, which means their contents is copied when they are assigned to another value, or passed to another function/method. Therefore, you do not need to worry about whether a receiving method function might change the original array. Therefore you don't need to ensure to return an immutable collection if your class is holding a mutable collection, for instance.

不可变/可变集合的其他用途取决于您希望它们可变/不可变的原因。集合是Swift中的类型,这意味着它们的内容在被分配给另一个值或传递给另一个函数/方法时会被复制。因此,您无需担心接收方法函数是否会更改原始数组。因此,例如,如果您的类持有可变集合,则无需确保返回不可变集合。

回答by Ved Rauniyar

There's no built-in cast for this. But instead you can use NSMutableDictionary's initializer that takes a dictionary:

没有为此内置演员表。但是,您可以使用 NSMutableDictionary 的带有字典的初始化程序:

var foundationDictionary = NSMutableDictionary(dictionary: dictionary)