Last active
June 17, 2020 03:36
-
-
Save stleamist/11ed51d5a59909b4b871989406fcdad2 to your computer and use it in GitHub Desktop.
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 | |
@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