Created
March 19, 2019 02:29
-
-
Save matsuda/5396498e8239280ba438e92f46b29689 to your computer and use it in GitHub Desktop.
Codable拡張
This file contains 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
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