2 // Dictionary+OAuthSwift.swift
5 // Created by Dongri Jin on 6/21/14.
6 // Copyright (c) 2014 Dongri Jin. All rights reserved.
11 extension Dictionary {
13 func join(_ other: Dictionary) -> Dictionary {
14 var joinedDictionary = Dictionary()
16 for (key, value) in self {
17 joinedDictionary.updateValue(value, forKey: key)
20 for (key, value) in other {
21 joinedDictionary.updateValue(value, forKey: key)
24 return joinedDictionary
27 var urlEncodedQuery: String {
28 var parts = [String]()
30 for (key, value) in self {
31 let keyString = "\(key)".urlEncoded
32 let valueString = "\(value)".urlEncoded
33 let query = "\(keyString)=\(valueString)"
37 return parts.joined(separator: "&")
40 mutating func merge<K, V>(_ dictionaries: Dictionary<K, V>...) {
41 for dict in dictionaries {
42 for (key, value) in dict {
43 if let v = value as? Value, let k = key as? Key {
44 self.updateValue(v, forKey: k)
50 func map<K: Hashable, V> (_ transform: (Key, Value) -> (K, V)) -> [K: V] {
51 var results: [K: V] = [:]
53 if let value = self[ k ] {
54 let (u, w) = transform(k, value)
55 results.updateValue(w, forKey: u)
62 extension Dictionary {
63 @available(swift, introduced: 3.2, obsoleted: 4.0)
64 public func filter(_ isIncluded: (Key, Value) throws -> Bool) rethrows -> [Key: Value] {
65 var resultDictionary = [Key: Value](minimumCapacity: count)
66 for (key, value) in self {
67 if try isIncluded(key, value) {
68 resultDictionary[key] = value
71 return resultDictionary
75 func +=<K, V> (left: inout [K: V], right: [K: V]) { left.merge(right) }
76 func +<K, V> (left: [K: V], right: [K: V]) -> [K: V] { return left.join(right) }
77 func +=<K, V> (left: inout [K: V]?, right: [K: V]) {
78 if left != nil { left?.merge(right) } else { left = right }