[英]Swift Dictionary sorted keys extension
I'm using a Dictionary's keys as the datasource
of my tableview
. 我正在使用Dictionary的键作为
tableview
的datasource
。 The Dictionary's type is [String: [Question]]
. 字典的类型为
[String: [Question]]
。
The problem is that the array returned from Dictionary.keys
is not a sorted array, but I want it to be sorted. 问题是从
Dictionary.keys
返回的数组不是经过排序的数组,但是我希望对其进行排序。 Create a function to sort the keys array could be a solution, but it's not decent enough for me, because you have to call that function every time you access the keys. 创建一个用于对键数组进行排序的函数可能是一个解决方案,但是这对我来说还不够好,因为每次访问键时都必须调用该函数。
One idea came out of my mine is, to make an extension of Dictionary , something like this, 我的想法是,对Dictionary进行扩展,像这样,
extension Dictionary where Key: StringLiteralConvertible {
var sortedKeys: [String] {
get {
return keys.sort{ $0.0 > $1.0 }
}
}
}
But it tells me that "Type is expression is ambiguous without more context". 但是它告诉我“类型是表达式在没有更多上下文的情况下是模棱两可的”。 Can anyone tell me if this is possible?
谁能告诉我这是否可能?
extension Dictionary where Key: Comparable {
var sortedKeys: [Key] {
get {
return keys.sort{ $0 > $1 }
}
}
}
To use >
, Key
needs to be Comparable
. 要使用
>
, Key
必须是可Comparable
。 (This ordering is what you want? You use <
for ascending order.) (此顺序是您想要的?您将
<
用作升序。)
This extension works for Dictionary
where Key
may not be String
. 此扩展适用于
Key
不能为String
Dictionary
。
In keys.sort
, $0
and $1
are of type Key
, not (Key, Value)
. 在
keys.sort
, $0
和$1
属于Key
类型,而不是(Key, Value)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.