Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save minsOne/bc6cb5301f021daef6894c27744017b9 to your computer and use it in GitHub Desktop.

Select an option

Save minsOne/bc6cb5301f021daef6894c27744017b9 to your computer and use it in GitHub Desktop.
Swift Codable to URL Query String
import Foundation
import DictionaryCoding
/// Note: This relies on the DictionaryCoding package https://github.com/elegantchaos/DictionaryCoding
struct QueryParamEncoder {
func encode<T: Encodable>(_ item: T) throws -> String {
let encoder = DictionaryEncoder()
let encoded: [String: Any] = try encoder.encode(item)
let queryParams = encodeDictionary(encoded)
return "?\(queryParams)"
}
private func encodeDictionary(_ dictionary: [String: Any]) -> String {
return dictionary
.compactMap { (key, value) -> String? in
if value is [String: Any] {
if let dictionary = value as? [String: Any] {
return encodeDictionary(dictionary)
}
}
else {
return "\(key)=\(value)"
}
return nil
}
.joined(separator: "&")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment