Swift中的有序字典

时间:2015-06-21 21:51:49

标签: ios swift dictionary swift2

是否有任何内置方法在Swift 2中创建有序地图?数组workingDirec = raw_input("What is the working directory?") original_file = raw_input("The input filename is?") def calculateZscore(): "Z score calc" full_original = os.path.join(workingDirec,original_file) print full_original f = open ('C:\Users\tpmorris\ProgramingAndScripting\Trial 2 Data\Trial 2 Data\NCSIDS_ObsExp.txt','r') print f 按照对象附加到它的顺序排序,但字典[T]没有排序。

例如

[K : V]

是否有任何内置方法可以创建有序的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) 地图,其排序方式与数组相同,或者我是否必须创建自己的类?

如果可能的话,我想避免创建自己的类,因为Swift包含的内容很可能更有效。

13 个答案:

答案 0 :(得分:32)

只需使用一组元组代替。按你喜欢的方式排序。所有“内置”。

if(dur > 0 && maxDur > 0) {
    var newDur = ((1-(dur / maxDur)) * 60)+"px";
    var newDur2 = ((dur / maxDur) * 60)+"px";
    console.log(newDur + " dur " + newDur2) --> returns "58.5px dur 1.5px"

    $("#dDur").css({ width: newDur });
    $("#dDur2").css({ width: newDur2 });
    $("#").css({ border: '2px solid '+bonusColor });
    detailString += "<div class='dDur' width='"+newDur+"'></div>
    <div class='dDur2' width='"+newDur2+"'> </div>";
}

答案 1 :(得分:28)

您可以使用Int类型的键来订购它们。

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

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

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

答案 2 :(得分:21)

“如果您需要有序的键值对集合,并且不需要Dictionary提供的快速键查找,请参阅DictionaryLiteral类型以获取替代方案。” - https://developer.apple.com/reference/swift/dictionary

答案 3 :(得分:6)

正如Matt所说,词典(和集合)是Swift(以及Objective-C)中的无序集合。这是设计的。

如果您愿意,可以创建字典键的数组,并将其排序为您想要的任何顺序,然后使用它从字典中提取项目。

NSDictionary有一个方法allKeys,它为您提供数组中字典的所有键。我似乎记得类似于Swift Dictionary对象的东西,但我不确定。我还在学习斯威夫特的细微差别。

编辑:

对于Swift Dictionaries,它是someDictionary.keys

答案 4 :(得分:3)

Swift不包含任何内置的有序字典功能,据我所知,Swift 2也没有

然后你应该创建自己的。您可以查看这些教程以获取帮助:

答案 5 :(得分:3)

如果您的密钥确认为Comparable,您可以从未排序的字典创建一个排序字典,如下所示

let sortedDictionary = unsortedDictionary.sorted() { $0.key > $1.key }

答案 6 :(得分:1)

我知道我参加了聚会,但你是否考虑过NSMutableOrderedSet?

https://developer.apple.com/reference/foundation/nsorderedset

  

当顺序为时,您可以使用有序集作为数组的替代   元素在测试对象是否重要方面很重要   包含在集合中的是对成员资格的考虑测试   数组比测试集合的成员资格要慢。

答案 7 :(得分:1)

您可以使用来自原始 Swift Repo

的官方 OrderedDictionary

有序集合当前包含:

他们说它很快就会被合并到 Swift 本身中(在 WWDC21 中)

答案 8 :(得分:0)

    var orderedDictionary = [(key:String, value:String)]()

答案 9 :(得分:0)

正如其他人所说,这种类型的结构没有内置支持。他们可能会在某个时候将实现添加到标准库中,但是鉴于相对很少在大多数应用程序中成为最佳解决方案,所以我不会屏息。

一个替代方案是OrderedDictionary项目。由于它遵循<div id="Cumulative GPA" class="tabcontent"> <ul> <li> <label> <span>Cumulative GPA <b>before</b> this semester:</span> <input type="number" min="0" max="4" step="1" id="oldcumulativegpa" value="4" placeholder="Cumulative GPA"> </label> </li> <li> <label> <span><b>Number of semesters</b> your Old Cumulative GPA was calculated with:</span> <input type="number" min="1" step="1" placeholder="Number of semesters" id="numberofsemesters" value="3"> </label> </li> <li> <label> <span>Your GPA <b>this semester</b>:</span> <input type="number" min="0" max="4" step="1" value="3" placeholder="GPA this semester" id="currentsemestergpa"> </label> </li> </ul> </div> <label for="newcumulativegpa">Your New Cumulative GPA:</label> <output id="newcumulativegpa" for="oldcumulativegpa numberofsemesters currentsemestergpa" name="newcumulativegpa">0</output>,因此您可以获得与其他BidirectionalCollection类型通常使用的大多数相同的API,并且(目前)似乎维护得相当好。

答案 10 :(得分:0)

您可以使用KeyValuePairs, 来自documentation

  

当您需要一个有序的键-值对集合并且不需要Dictionary类型提供的快速键查找时,请使用KeyValuePairs实例。

let pairs: KeyValuePairs = ["john": 1,"ben": 2,"bob": 3,"hans": 4]
print(pairs.first!)

// prints(键:“ john”,值:1)

答案 11 :(得分:-1)

这就是我所做的,非常简单:

let array = [
    ["foo": "bar"],
    ["foo": "bar"],
    ["foo": "bar"],
    ["foo": "bar"],
    ["foo": "bar"],
    ["foo": "bar"]
]

// usage
for item in array {
    let key = item.keys.first!
    let value = item.values.first!

    print(key, value)
}

键不是唯一的,因为它不是Dictionary而是Array,但是您可以使用数组键。

答案 12 :(得分:-6)

使用Dictionary.enumerated()

示例:

let dict = [
    "foo": 1,
    "bar": 2,
    "baz": 3,
    "hoge": 4,
    "qux": 5
]


for (offset: offset, element: (key: key, value: value)) in dict.enumerated() {
    print("\(offset): '\(key)':\(value)")
}
// Prints "0: 'bar':2"
// Prints "1: 'hoge':4"
// Prints "2: 'qux':5"
// Prints "3: 'baz':3"
// Prints "4: 'foo':1"