Skip to content

Instantly share code, notes, and snippets.

@stleamist
Last active June 17, 2020 03:36
Show Gist options
  • Save stleamist/11ed51d5a59909b4b871989406fcdad2 to your computer and use it in GitHub Desktop.
Save stleamist/11ed51d5a59909b4b871989406fcdad2 to your computer and use it in GitHub Desktop.
import Foundation
@propertyWrapper
public struct PercentEncodedURL: Codable {
public let wrappedValue: URL
public init(wrappedValue: URL) {
self.wrappedValue = wrappedValue
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self.wrappedValue = try container.decode(URL.self)
} catch(let error) {
guard
let urlString = try? container.decode(String.self),
let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let encodedURL = URL(string: encodedURLString) else {
throw error
}
self.wrappedValue = encodedURL
}
}
public func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment