Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save martinhoeller/31984a199bb7dac27c743d05555a0894 to your computer and use it in GitHub Desktop.
Save martinhoeller/31984a199bb7dac27c743d05555a0894 to your computer and use it in GitHub Desktop.
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