Skip to content

Instantly share code, notes, and snippets.

@RobertMenke
Last active February 28, 2023 10:24
Show Gist options
  • Save RobertMenke/ae3a012062b046dc5974819b01285ea9 to your computer and use it in GitHub Desktop.
Save RobertMenke/ae3a012062b046dc5974819b01285ea9 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