我开发了下面的算法来对字典项数组进行排序。

guard var imageUrlString = anyImage.value as? [String:AnyObject] else { return }

var values = [AnyObject]()
var keys = [String]()
var done = false
var j = 1

while !done {
    for i in imageUrlString {
        print(i.key, " this is the key")
        if "media\(j)" == i.key {
            values.append(i.value)
            keys.append(i.key)
            print(i, " This is teh i for in if ")
            if imageUrlString.count == j {
                done = true
                break;
            }
            j+=1
        } else {
            print("No,,.")
        }
    }
}

问题是,有时,例如,每次第一个媒体是一个图像,它将永远循环。如何解决这个问题,以便算法能够在所有条件下有效地排序?

最佳答案

看起来你真的在创建两个并行数组:keysvalues
我继续创建这两个数组,排序。这里有一个例子

var imageUrlString = [String: AnyObject]()
imageUrlString["media3"] = "whatever 3 content" as AnyObject
imageUrlString["media7"] = "whatever 7 content" as AnyObject
imageUrlString["media1"] = "whatever 1 content" as AnyObject

let keys = Array(imageUrlString.keys).sorted()
var values = [AnyObject]()

keys.forEach {
    values.append(imageUrlString[$0]!)
}

print(keys)
print(values)

10-01 16:49