Last active
September 7, 2020 11:36
-
-
Save molind/94b750bdd6c603d608b2310f6be5f050 to your computer and use it in GitHub Desktop.
SortedDictionary used to sort contents before JSON serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) | |
} | |
} | |
} |
@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
@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]