Skip to content

Instantly share code, notes, and snippets.

@matsuda
Created March 19, 2019 02:29
Show Gist options
  • Save matsuda/5396498e8239280ba438e92f46b29689 to your computer and use it in GitHub Desktop.
Save matsuda/5396498e8239280ba438e92f46b29689 to your computer and use it in GitHub Desktop.
Codable拡張
internal extension KeyedDecodingContainer {
/// 不正なurlだとdecodeエラーになるので、nilにしてスルーする
/// @see https://github.com/apple/swift/blob/master/stdlib/public/Darwin/Foundation/URL.swift
/// @see https://github.com/apple/swift/blob/master/stdlib/public/core/Codable.swift.gyb
/// @see https://github.com/apple/swift/blob/master/stdlib/public/Darwin/Foundation/JSONEncoder.swift
func decodeIfPresent(_ type: URL.Type, forKey key: K) throws -> URL? {
guard try contains(key) && !decodeNil(forKey: key)
else { return nil }
do {
return try decode(URL.self, forKey: key)
} catch DecodingError.dataCorrupted {
return nil
} catch {
throw error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment