Created
May 29, 2020 08:35
-
-
Save martinhoeller/31984a199bb7dac27c743d05555a0894 to your computer and use it in GitHub Desktop.
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
import Foundation | |
extension KeyedDecodingContainerProtocol { | |
/** | |
Decodes a value of the given type for the given key, providing a default value if the value could not be decoded. | |
- parameter type: The type of value to decode. | |
- parameter key: The key that the decoded value is associated with. | |
- parameter defaultValue: The default value that is used if the a value for `key` could not be decoded. | |
- returns: A value of the requested type, if present for the given key and convertible to the requested type, or `defaultValue` if the value could not be decoded. | |
*/ | |
func decode<T>(_ type: T.Type, forKey key: Self.Key, defaultValue: T) -> T where T : Decodable { | |
return (try? decode(type, forKey: key)) ?? defaultValue | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment