Skip to content

Instantly share code, notes, and snippets.

@molind
Last active September 7, 2020 11:36
Show Gist options
  • Save molind/94b750bdd6c603d608b2310f6be5f050 to your computer and use it in GitHub Desktop.
Save molind/94b750bdd6c603d608b2310f6be5f050 to your computer and use it in GitHub Desktop.
SortedDictionary used to sort contents before JSON serialization
// We have a parent just to pass face control in JSONSerialization
@objc class SortedDictionary: NSDictionary {
let _values: NSMutableArray = []
let _keys: NSMutableOrderedSet = []
override var count: Int {
return _keys.count
}
override func keyEnumerator() -> NSEnumerator {
return _keys.objectEnumerator()
}
override func object(forKey aKey: Any) -> Any? {
let index = _keys.index(of: aKey)
if index != NSNotFound {
return _values[index]
}
return nil
}
private func setObject(_ anObject: Any, forKey aKey: String) {
let index = _keys.index(of: aKey)
if index != NSNotFound {
_values[index] = convertObject(anObject)
} else {
_keys.add(aKey)
_values.add(convertObject(anObject))
}
}
private func convertObject(_ object: Any) -> Any {
if let dict = object as? [String: Any] {
return SortedDictionary(dict)
} else if let array = object as? [Any] {
return array.map {
convertObject($0)
}
} else {
return object
}
}
@objc convenience init(_ dictionary: [String: Any]) {
self.init()
dictionary.sorted {
$0.0.compare($1.0, options: [.caseInsensitive, .forcedOrdering]) == .orderedAscending
}
.forEach {
self.setObject($0.value, forKey: $0.key)
}
}
}
@Coeur
Copy link

Coeur commented Feb 3, 2020

@molind I found a sorting bug: "a" and "A" will be randomized, so the output will not be stable. It can be fixed by specifying [.forcedOrdering, .caseInsensitive]

@molind
Copy link
Author

molind commented Feb 10, 2020

@molind I found a sorting bug: "a" and "A" will be randomized, so the output will not be stable. It can be fixed by specifying [.forcedOrdering, .caseInsensitive]

Thanks for mentioning this. I'll update gist right now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment