[swift-evolution] Generic Subscripts

Gwendal Roué gwendal.roue at gmail.com
Sat Jan 14 13:05:02 CST 2017


> Le 14 janv. 2017 à 18:45, Anton Zhilin <antonyzhilin at gmail.com> a écrit :
> 
> I’m not sure, but I think that in this case the specific type of these values is determined at runtime.
> Then a safe approach would be separate string: String?, bool: Bool?, int: Int? computed properties, as it’s done in JSON parsers.
> 
> if let bookCount = row.value(named: "bookCount").int {
>     ...
> }
> if let bookCount = row["bookCount"].int {
>     ...
> }
> let bookCount = row.int <http://row.int/>("bookCount")!   // crash if database is corrupt
> Additionally, this is an overall bad example of generics. Fields of database tables can only map to a limited set of static types in Swift, which are supported by database adapter
> 
Thanks for the compliment! I disagree, of course.

App developers may need to fetch basic database data types, obviously, but also RawRepresentable types based on those types, dates, date components, uuids, serialized JSON, and generally speaking a large and extensible set of serializable types.

This is, I believe, a very good usage of return type genericity, as well as an excellent opportunity for the open/closed principle (https://en.wikipedia.org/wiki/Open/closed_principle <https://en.wikipedia.org/wiki/Open/closed_principle>).

Gwendal

> 2017-01-14 16:50 GMT+03:00 Gwendal Roué via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>>:
> 
> As the developer of a Swift database library, I'd like to offer a better API than the following:
> 
>     // Current state of affairs
>     let name: String = row.value(named: "name")
>     let bookCount: Int = row.value(named: "bookCount")
>     let hasBooks: Bool = row.value(named: "bookCount")
> 
> Instead, I wish I could offer GRDB.swift would let its users write:
> 
>     // With improved subscripts
>     let name: String = row["name"]
>     let bookCount: Int = row["bookCount"]
>     let hasBooks: Bool = row["bookCount"]
> 
> And this requires genericity on return type.
> 
> Gwendal
> 
> 
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org <mailto:swift-evolution at swift.org>
> https://lists.swift.org/mailman/listinfo/swift-evolution <https://lists.swift.org/mailman/listinfo/swift-evolution>
> 
> 
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170114/94e2ad9d/attachment.html>


More information about the swift-evolution mailing list