ios 元组与字典的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27631137/
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 04:07:04  来源:igfitidea点击:

Tuple vs Dictionary differences

iosswift

提问by Phil

Can someone please explain what the major differences there are between Tuples and Dictionaries are and when to use which in Swift?

有人可以解释一下元组和字典之间的主要区别是什么以及何时在 Swift 中使用哪个?

回答by Midhun MP

Major difference:

主要区别:

  • If you need to return multiple values from a method you can use tuple.
  • Tuple won't need any key value pairs like Dictionary.
  • A tuple can contain only the predefined number of values, in dictionary there is no such limitation.
  • A tuple can contain different values with different datatype while a dictionary can contain only one datatype value at a time
  • Tuples are particularly useful for returning multiple values from a function. A dictionary can be used as a model object.
  • 如果您需要从一个方法返回多个值,您可以使用元组。
  • Tuple 不需要像 Dictionary 这样的任何键值对。
  • 元组只能包含预定义数量的值,字典中没有这样的限制。
  • 元组可以包含不同数据类型的不同值,而字典一次只能包含一个数据类型值
  • 元组对于从函数返回多个值特别有用。字典可以用作模型对象。


There are two types of Tuple:

有两种类型的元组:

1 Named Tuple

1 命名元组

In Named tuple we assign individual names to each elements.

在命名元组中,我们为每个元素分配单独的名称。

Define it like:

像这样定义:

let nameAndAge = (name:"Midhun", age:7)

Access the values like:

访问如下值:

nameAndAge.name
nameAndAge.age


2 Unnamed Tuple

2 未命名元组

In unnamed tuple we don't specify the name for it's elements.

在未命名元组中,我们不指定其元素的名称。

Define it like:

像这样定义:

let nameAndAge = ("Midhun", 7)

Access the values like:

访问如下值:

nameAndAge.0
nameAndAge.1

or

或者

let (theName, thAge) = nameAndAge
theName
thAge


Reference:

参考:

Tuple

元组

Tuples enable you to create and pass around groupings of values. You can use a tuple to return multiple values from a function as a single compound value.

元组使您能够创建和传递值的分组。您可以使用元组将函数中的多个值作为单个复合值返回。

You can check more about Tuple in Swift Programming Language

您可以在Swift 编程语言中查看有关 Tuple 的更多信息

Dictionary

字典

A dictionary is a container that stores multiple values of the same type. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary

字典是存储多个相同类型值的容器。每个值都与一个唯一键相关联,该键充当字典中该值的标识符

You can check more about Dictionary in Swift CollectionTypes

您可以在Swift CollectionTypes 中查看有关 Dictionary 的更多信息

回答by matt

  • A tuple is completely predefined: it can only have the names and number of values you've predefined for it, though they can be differentvalue types, and they don't have to have names. And the names are literals.

  • A dictionary can have any number of key-value pairs, of onevalue type. And the keys can be referred to through variables.

  • 元组是完全预定义的:它只能具有您为其预定义的名称和值的数量,尽管它们可以是不同的值类型,并且它们不必具有名称。名称是文字。

  • 字典可以有任意数量的键值对,属于一种值类型。并且可以通过变量引用键。



Here's a tuple (with names):

这是一个元组(带有名称):

typealias MySillyTuple = (theInt:Int, theString:String)

That's it. There is one Int called theInt, one String called theString, and that is exactly what it must have, no more, no less. And the only way to access the values by name is as a literal: t.theInt. If you have a string "theInt", you can't use it to access t.theInt.

就是这样。有一个 Int 称为theInt,一个 String 称为theString,这正是它必须拥有的,不多也不少。按名称访问值的唯一方法是作为文字:t.theInt. 如果您有一个 string "theInt",则不能使用它来访问t.theInt.

Here's a Dictionary:

这是一个字典:

var d = [String:String]()

Now dcan have any number of keys, and anykeys, from none to a gazillion. And the keys can be specified using string variables; you don't have to know in advance what a key will be. And all the values must be strings.

现在d可以拥有任意数量的密钥,任何密钥,从无到无数。并且可以使用字符串变量指定键;您不必事先知道密钥是什么。并且所有的值都必须是字符串。

So basically I would say a tuple is nothing like a dictionary. A dictionary is a complex beast for look up by dynamic keys. A tuple is just a value that is more than one value.

所以基本上我会说元组不像字典。字典是通过动态键查找的复杂野兽。元组只是一个不止一个值的值。

回答by arthankamal

  1. Dictionaryis Collection Type, Tupleis Compound type.
  2. Dictionaryis Key Valuetype, Tupleis Comma separated list of multiple types
  1. DictionaryCollection TypeTupleCompound type
  2. DictionaryKey Value类型,TupleComma separated list of multiple types

Dictionary:

var dictionary = ["keyone": "value one", "keytwo": "Value Two"]

Tuple:

字典:

var dictionary = ["keyone": "value one", "keytwo": "Value Two"]

元组:

let someTuple: (Double, Double, String, (Int, Int)) = (3.14159, 2.71828, "Hello", (2, 3))

回答by 67cherries

A dictionary is made up of key-value sets. A tuple is made for passing grouped values.

字典由键值集组成。元组用于传递分组值。

Dictionaries:

字典:

A dictionary is a container that stores multiple values of the same type. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary.

字典是存储多个相同类型值的容器。每个值都与一个唯一键相关联,该键充当字典中该值的标识符。

A dictionary should be used for creating lists of associated objects. An example use would be a dictionary of players and their scores:

应该使用字典来创建关联对象的列表。一个示例用途是玩家及其分数的字典:

var scoreDictionary = ["Alice" : 100, "Bob" : 700]

Tuples:

元组

Tuples group multiple values into a single compound value.

元组将多个值分组为一个复合值。

A tuple should be used for passing groups of values. They are similar to arrays, but are fixed-length and immutable. An example use might be a tuple representing a 3-dimensional point:

应该使用元组来传递值组。它们类似于数组,但长度固定且不可变。一个示例用途可能是表示 3 维点的元组:

var myPoint = (10, 12, 14)


As you can see there are many cases in which you would use a dictionary and many cases in which you would use a tuple. Each has its own specific purpose.

正如你所看到的,在很多情况下你会使用字典,很多情况下你会使用元组。每个都有其特定的目的。

回答by jwlaughton

Tuples are compound values, and can be useful for functions returning several values from a function. e.g. (from the Apple Docs):

元组是复合值,对于从函数返回多个值的函数很有用。例如(来自苹果文档):

func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0

    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }

    return (min, max, sum)
}

This function returns a tuple containing min, max and sum. These values can be accessed either by name or position:

此函数返回一个包含 min、max 和 sum 的元组。这些值可以通过名称或位置访问:

let statistics = calculateStatistics([5, 3, 100, 3, 9])
var sum:Int = statistics.sum
var sum2:Int = statistics.2

Dictionaries are "lookup" data types. They return an object for a given key. For example the following code:

字典是“查找”数据类型。它们为给定的键返回一个对象。例如下面的代码:

let font:NSFont = NSFont(name: "AppleCasual", size: 18.0)!
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.LeftTextAlignment
let textColor:NSColor = NSColor(calibratedRed: 1.0, green: 0.0, blue: 1.0, alpha: 1.0)

let attribs = [NSFontAttributeName: font,
        NSForegroundColorAttributeName: textColor,
        NSParagraphStyleAttributeName: textStyle]

let color = attribs[NSForegroundColorAttributeName]

println("color = \(color)")

Will print:

将打印:

color = Optional(NSCalibratedRGBColorSpace 1 0 1 1)

颜色 = 可选(NSCalibratedRGBColorSpace 1 0 1 1)

Dictionaries are useful for many things and are required for some functions. For example (after the code above):

字典对很多事情都很有用,并且是某些功能所必需的。例如(在上面的代码之后):

let testString:NSString = "test String"
var img:NSImage = NSImage(size: NSMakeSize(200,200))
img.lockFocus()
testString.drawAtPoint(NSMakePoint(0.0, 0.0), withAttributes: attribs)    
img.unlockFocus()

In this code drawAtPoint uses the dictionary attribs to lookup the parameters it needs. The parameters don't need to be in any specific order because drawAtPoint will lookup the values it needs by using the correct key.

在这段代码中,drawAtPoint 使用字典 attribs 来查找它需要的参数。参数不需要按任何特定顺序排列,因为 drawAtPoint 将使用正确的键查找它需要的值。

Dictionaries and tuples are similar, but not quite the same. In the code above the dictionary returned an Optional type:Optional(NSCalibratedRGBColorSpace 1 0 1 1)

字典和元组相似,但又不完全相同。在上面的代码中,字典返回了一个 Optional 类型:Optional(NSCalibratedRGBColorSpace 1 0 1 1)

If we use a tuple for the same purpose:

如果我们出于相同目的使用元组:

var attribTuple = (font:NSFont(name: "AppleCasual", size: 18.0), color:NSColor(calibratedRed: 1.0, green: 0.0, blue: 1.0, alpha: 1.0))

println("tupleColor = \(attribTuple.color)")

Prints:

印刷:

tupleColor = NSCalibratedRGBColorSpace 1 0 1 1

元组颜色 = NSCalibratedRGBColorSpace 1 0 1 1

Not the optional type the dictionary did.

不是字典所做的可选类型。

回答by Airspeed Velocity

Tuples are fixed-length things. You can't add an extra element to a tuple or remove one. Once you create a tuple it has the same number of elements – var t = (1,2)is of type (Int,Int). It can never become (1,2,3), the most you could do is change it to, say, (7,8). This is all fixed at compile-time.

元组是固定长度的东西。您不能向元组添加额外的元素或删除一个元素。创建元组后,它具有相同数量的元素 -var t = (1,2)类型为(Int,Int)。它永远不会变成(1,2,3),您最多只能将其更改为 ,例如(7,8)。这都是在编译时修复的。

You can access the elements via their numeric positions like this

您可以像这样通过它们的数字位置访问元素

t.0 + t.1  // with (1,2), would equal 3
t.0 = 7

Arrays are variable length: you can start with an array var a = [1,2], and then add an entry via a.append(3)to make it [1,2,3]. You can tell how many items with a.count. You can access/update elements via a subscript: a[0] + a[2] // equals 4

数组是可变长度的:您可以从一个数组开始var a = [1,2],然后添加一个条目 viaa.append(3)使其成为[1,2,3]。您可以通过a.count. 您可以通过下标访问/更新元素:a[0] + a[2] // equals 4

You can name the elements in tuples:

您可以命名元组中的元素:

var n = (foo: 1, bar: 2)

Then you can use those names:

然后你可以使用这些名称:

n.foo + n.bar  // equals 3

This doesn't remove the ability to access them by position though:

不过,这并不会取消按位置访问它们的能力:

n.0 + n.1  // equals 3 

But these names, once set, are fixed at compile time just like the length:

但是这些名称一旦设置,就像长度一样在编译时固定:

n.blarg  // will fail to compile

This is not the same as dictionaries, which (like arrays), can grow or shrink:

这与字典不同,字典(如数组)可以增长或缩小:

var d = [“foo”:1, “bar”:2]
d[“baz”] = 3; 
d[“blarg”] // returns nil at runtime, there's no such element