Created
September 28, 2018 10:18
-
-
Save yuseinishiyama/e6904f0b07b61f23f2f3597b1359fc2c to your computer and use it in GitHub Desktop.
Safe Decode
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
public protocol DefaultValueProviding { | |
static var defaultValue: Self { get } | |
} | |
extension String: DefaultValueProviding { | |
public static var defaultValue: String { return "" } | |
} | |
extension Int: DefaultValueProviding { | |
public static var defaultValue: Int { return 0 } | |
} | |
extension KeyedDecodingContainer { | |
/// It works the same as the foundation `decodeIfPresent` but infers the type of | |
/// value to decode from the context. | |
public func decodeIfPresent<T: Decodable>(forkey key: Key) throws -> T? { | |
return try decodeIfPresent(T.self, forKey: key) | |
} | |
/// Decodes a value of the inferred type, or returns the default value if the value | |
/// is a null value, or if there are no more elements to decode, or if the type of | |
/// the element doesn't match the inferred type. | |
public func decodeSafelyIfPresent<T: Decodable>(forKey key: Key, defaultValue: T) -> T { | |
do { | |
return try decodeIfPresent(T.self, forKey: key) ?? defaultValue | |
} catch { | |
return defaultValue | |
} | |
} | |
/// Decodes a value of the inferred type, or returns the default value provided | |
/// using `DefaultValueProviding` protocol if the value is a null value, | |
/// or if there are no more elements to decode, or if the type of the element | |
/// doesn't match the inferred type. | |
public func decodeSafelyIfPresent<T: Decodable & DefaultValueProviding>(forKey key: Key) -> T { | |
return decodeSafelyIfPresent(forKey: key, defaultValue: T.defaultValue) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment