Skip to content

Instantly share code, notes, and snippets.

@gonzalezreal
Last active July 13, 2022 11:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gonzalezreal/e20bc13780f4b054fe15941fac638770 to your computer and use it in GitHub Desktop.
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.
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
}
}
@kevinhermawan
Copy link

Nice extension!

New update: stringValue.trimmingWhiteSpace => stringValue.trimmingCharacters(in: .whitespacesAndNewlines) :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment