3 ms·
Swift supports this. Having said that, I don't think I've encountered it in the standard library. I recently started using the Decodable protocol and was surpr
by fphilipe 9y ago
Swift supports this. Having said that, I don't think I've encountered it in the standard library.
I recently started using the Decodable protocol and was surprised to find out that the `decode` methods all take an explicit type, e.g. `KeyedDecodingContainer.decode(Double.Type, forKey: KeyedDecodingContainer.Key)`. There's a method for each supported type. [1]
Not sure why they didn't just have one method to rule them all in the public interface, like this:
extension KeyedDecodingContainer {
public func decode<T: Decodable>(key: KeyedDecodingContainer.Key) throws -> T {
return try decode(T.self, forKey: key)
}
}
The usage then becomes much simpler (assume `name` is a property of type `String`):
// Before:
name = try container.decode(String.self, forKey: .name)
// After:
name = try container.decode(key: .name)
[1]: https://developer.apple.com/documentation/swift/keyeddecodingcontainer https://developer.apple.com/documentation/swift/keyeddecodin...