Ordered Dictionary in JSON

前端 未结 4 1722
梦毁少年i
梦毁少年i 2020-12-21 16:28

There are 3 string variables

public var userLoginId : String?
public var searchString : String?
public var tableName : String?

I have a dic

4条回答
  •  一整个雨季
    2020-12-21 16:45

    Not only does Swift's Dictionary not have ordering, but neither do JSON dictionaries, as per the standard. The best you could probably do is store the keys, in correct order, in an array. Instead of iterating the dictionary, you instead iterate the ordered array of keys, and then fetch from the dictionary with those keys.

    To avoid repeating the keys manually, you can express your dictionary as an array of (Key, Value) tuples, like so:

    let keyValuePairs = [
        ("userLoginId", userLoginId),
        ("searchString", searchString),
        ("tableName", tableName)
    ]
    
    
    let dict = Dictionary(uniqueKeysWithValues: keyValuePairs)
    let orderedKeys = keyValuePairs.map { $0.0 }
    

    Now you can use the orderedKeys in your Swift code, or store them in JSON alongside the dict:

    print("Example usage:")
    for key in orderedKeys {
        let value = dict[key]!
        
        print("\(key): \(value)")
    }
    

提交回复
热议问题