这是使用内置的排序功能Dictionary
■一个可能的解决方案进行排序,但呈现title
财产在你的例子定制enum
而非String
。然后通过enum
中月份的排序隐式给出“分类模板”。
也就是说,enum MonthSortTemplate
和你MyClass
类(后者还没有洗澡了我们,所以我做了一个MWE自己)为:
enum MonthSortTemplate: Int {
case April = 1
case January
case February
// ... rest of months follows, in the order you prefer
}
class MyClass {
var price = ""
var value = ""
var title: MonthSortTemplate = .April
}
// Hashable (just some dummy, don't know how you've set this up)
extension MyClass: Hashable {
var hashValue: Int {
return price.hashValue^value.hashValue
}
}
// Equatable (just some dummy, don't know how you've set this up)
func ==(lhs: MyClass, rhs: MyClass) -> Bool {
return lhs.price == rhs.price && lhs.value == rhs.value
}
创建MyClass
情况下,添加到您的字典,并使用.sort(...)
后者用于自定义闭合的功能,指定用于此特定类型的比较。
var Obj1 = MyClass()
var Obj2 = MyClass()
var Obj3 = MyClass()
Obj1.price = "10"
Obj1.value = "abc"
Obj1.title = .January
Obj2.price = "10"
Obj2.value = "def"
Obj2.title = .April
Obj3.price = "10"
Obj3.value = "pqr"
Obj3.title = .February
var dict = Dictionary<MyClass, Array<Int32>>()
dict = [ Obj1: [3,4], Obj2 : [1,2], Obj3: [8,9]]
// your custom sort closure, for Dictionary.sort(...) method
let byMonthTemplate = {
(elem1:(key: MyClass, val: [Int32]), elem2:(key: MyClass, val: [Int32]))->Bool in
if elem1.key.title.rawValue < elem2.key.title.rawValue {
return true
} else {
return false
}
}
let sortedDict = dict.sort(byMonthTemplate)
print("\(dict)")
另一种---如果你真的喜欢你的类属性title
是String
类型的---是定义<
运营商MyClass
对象:
func <(lhs: MyClass, rhs: MyClass) -> Bool {
// do comparison stuff with strings lhs.title and rhs.title
// with regard to your ordering of choice (array sortTemplate)
return ...
}
在这情况下,“杂乱”的东西最终在这个功能,而实际的排序可以执行相当优雅
let sortedDict = dict.sort { $0.0 < $1.0 }
就我个人而言,我更喜欢enum
解决方案(但是,这是脱离主题)。
编辑:
您的要求,我会为您的MyClass
类<
操作的一个例子。这绝不是最佳选择,但也许你可以从我的例子中改进它。
// add sortTemplate as a static property of MyClass
class MyClass {
var price = ""
var value = ""
var title = ""
static let sortTemplate = ["April", "May", "June", "July", "August", "September", "October", "November", "December", "January", "February", "March"]
}
// define < operator for MyClass objects
func <(lhs: MyClass, rhs: MyClass) -> Bool {
let indexOfLhs = MyClass.sortTemplate.indexOf({$0 == lhs.title})
let indexOfRhs = MyClass.sortTemplate.indexOf({$0 == rhs.title})
return indexOfLhs < indexOfRhs
}
// you can now sort your dictionary according to
let sortedDict = dict.sort { $0.0 < $1.0 }
请参阅此http://计算器。com/questions/30749219/ios-add-nsdictinary-key-values-into-an-nsarray-sequencialy/30749359#30749359 –
@SyedAliSalman为什么?他不希望数组中的字典的键。他只是希望他们排序。是否因为您对Objective-C中字典未排序的评论?我认为在Swift中他们可以对字典进行排序。 – NSNoob
你'月份的课程是否符合'Hashable'协议? – dfri