Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save martinhoeller/3c38da1492831b3668258f941d29c250 to your computer and use it in GitHub Desktop.
Save martinhoeller/3c38da1492831b3668258f941d29c250 to your computer and use it in GitHub Desktop.
/**
Decodes a value of the given type for the given key, providing a transform closure that converts the decoded value into another type.
- parameter type: The type of value to decode.
- parameter key: The key that the decoded value is associated with.
- parameter transform: A closure that transforms the decoded value into a value of a different type.
- returns: The value that was returned by the `transform` closure.
*/
func decode<T, R>(_ type: T.Type, forKey key: Self.Key, transform: (T) throws -> R) throws -> R where T : Decodable {
let rawValue = try decode(type, forKey: key)
return try transform(rawValue)
}
/**
Decodes an array of values of the given type for the given key, providing a transform closure that converts each element of the decoded array
into another type.
- parameter type: The array type of values to decode.
- parameter key: The key that the decoded array is associated with.
- parameter transform: A closure that transforms the elements of the decoded array into a values of a different type.
- returns: The value that was returned by the `transform` closure.
*/
func decode<T, R>(_ type: [T].Type, forKey key: Self.Key, transform: (T) throws -> R) throws -> [R] where T : Decodable {
let rawValues = try decode(type, forKey: key)
return try rawValues.map { try transform($0) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment