Swift中的有序地图 [英] Ordered map in Swift

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

问题描述

在Swift 2中是否有任何内置方法来创建有序地图?数组[T]按照对象附加到其的顺序进行排序,但字典[K : V]却不排序.

Is there any built-in way to create an ordered map in Swift 2? Arrays [T] are sorted by the order that objects are appended to it, but dictionaries [K : V] aren't ordered.

例如

var myArray: [String] = []
myArray.append("val1")
myArray.append("val2")
myArray.append("val3")

//will always print "val1, val2, val3"
print(myArray)


var myDictionary: [String : String] = [:]
myDictionary["key1"] = "val1"
myDictionary["key2"] = "val2"
myDictionary["key3"] = "val3"

//Will print "[key1: val1, key3: val3, key2: val2]"
//instead of "[key1: val1, key2: val2, key3: val3]"
print(myDictionary)

是否存在任何内置方法来创建有序key : value映射,该映射以与数组相同的方式进行排序,还是我必须创建自己的类?

Are there any built-in ways to create an ordered key : value map that is ordered in the same way that an array is, or will I have to create my own class?

我想尽可能避免创建自己的类,因为Swift所包含的任何内容都将最有效率.

I would like to avoid creating my own class if at all possible, because whatever is included by Swift would most likely be more efficient.

推荐答案

您可以通过使用类型为Int的键来订购它们.

You can order them by having keys with type Int.

var myDictionary: [Int: [String: String]]?

var myDictionary: [Int: (String, String)]?

我推荐第一个,因为它是一种更常见的格式(例如JSON).

I recommend the first one since it is a more common format (JSON for example).

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

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