Last active
February 28, 2023 10:24
-
-
Save RobertMenke/ae3a012062b046dc5974819b01285ea9 to your computer and use it in GitHub Desktop.
Swift Codable to URL Query String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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