[swift-evolution] [Draft] Throwing Properties and Subscripts

Jens Alfke jens at mooseyard.com
Mon Mar 14 19:31:33 CDT 2016


> 
>> Do you have an imagined use for throwing getters?

The project I work on — a database engine <https://github.com/couchbase/couchbase-lite-ios> — has an API with a lot of things that are conceptually properties, but whose accessors can fail because they may have to read or write persistent storage. Some examples are Database.documentCount and Document.currentRevision.

In the current (Objective-C) API, some of these are exposed as methods that use the standard Cocoa NSError-returning pattern, while some that are very unlikely to fail are exposed as actual properties; the implementations either return a distinct failure value like nil, or just a default value like 0. I’m not saying this is great, but it’s a tradeoff between correctness and ease of use where we’ve sometimes leaned toward ease of use.

Failable property accessors would be a big help here, letting us have an expressive API where properties are properties, while not losing the ability to do proper error handling.

The same applies to subscripts, btw. Since our data stores are key-value collections it’s convenient to be able to subscript a database by key to get a value. Of course this has the potential to fail due to file corruption, disk I/O errors, etc. 

As another example, I’ve done some experimental work in the past on incremental JSON parsing; if using such a library, errors are not necessarily discovered up front, so it’s possible for accessing an item in a JSON array or dictionary to fail with a parse error. (Yes, you could syntax-check ahead of time, but since the major purpose of the incremental parsing is speed, that would be self-defeating.)

—Jens
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160314/c7c15944/attachment.html>


More information about the swift-evolution mailing list