Last active
July 13, 2022 11:14
-
-
Save gonzalezreal/e20bc13780f4b054fe15941fac638770 to your computer and use it in GitHub Desktop.
A simple technique to trim whitespace from URLs before decoding them with Swift Codable.
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
public extension KeyedDecodingContainer { | |
func decode(_ type: URL.Type, forKey key: KeyedDecodingContainer.Key) throws -> URL { | |
let stringValue = try decode(String.self, forKey: key) | |
guard let url = URL(string: stringValue.trimmingWhiteSpace) else { | |
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Invalid URL string.") | |
} | |
return url | |
} | |
func decodeIfPresent(_ type: URL.Type, forKey key: KeyedDecodingContainer.Key) throws -> URL? { | |
guard let stringValue = try decodeIfPresent(String.self, forKey: key) else { | |
return nil | |
} | |
guard let url = URL(string: stringValue.trimmingWhiteSpace) else { | |
throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Invalid URL string.") | |
} | |
return url | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice extension!
New update:
stringValue.trimmingWhiteSpace
=>stringValue.trimmingCharacters(in: .whitespacesAndNewlines)
:)