Skip to content

Instantly share code, notes, and snippets.

@markiv
Last active January 11, 2018 13:22
Show Gist options
  • Save markiv/b79080273d94d5aa0d7f9a2869a43ed8 to your computer and use it in GitHub Desktop.
Save markiv/b79080273d94d5aa0d7f9a2869a43ed8 to your computer and use it in GitHub Desktop.
import Foundation
extension URLComponents {
/// Abstracts away URLComponent’s array of URLQueryItems into a simple dictionary
var parameters: [String: CustomStringConvertible] {
get {
return queryItems?.reduce(into: [String: String]()) { $0[$1.name] = $1.value } ?? [:]
}
set {
queryItems = newValue.map { URLQueryItem(name: $0.key, value: String(describing: $0.value)) }
}
}
}
// Example
var comps = URLComponents(string: "http://pepe.com:81/query?a=1")!
comps.parameters["b"] = 3 // URL is now http://pepe.com:81/query?b=3&a=1
comps.parameters["a"] = nil // http://pepe.com:81/query?b=3 (a is gone)
comps.parameters = ["name": "pepe", "age": 44, "dude": true, "date": Date()] // replace all query items
comps.url // http://pepe.com:81/query?name=pepe&age=44&date=2018-01-11%2013:19:47%20+0000&dude=true
// Reading too, of course:
comps.parameters["name"] // "pepe"
comps.parameters["age"] // "44"
comps.parameters["x"] // nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment