Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Change api to return optional values if keys do not exist #4

Closed
jdfergason opened this issue Aug 24, 2016 · 3 comments
Closed

Change api to return optional values if keys do not exist #4

jdfergason opened this issue Aug 24, 2016 · 3 comments

Comments

@jdfergason
Copy link
Owner

Currently Toml.value and variants throw an exception if a key does not exist. In practice this has created code that feels rather messy because simply grabbing a value requires a do { ... } catch { ... } block, a try! which is frowned upon, or propogating the error up with try and throws.

It would be more swifty to simply return an optional. If the key path requested does not exist then nil would be returned. Ie, Toml.value would become

 public func value<T>(_ path: String...) -> T?

And using the API would change from:

do {
    print(try toml.string("key", "path", "to", "value"))
} catch {
    // do something to handle the missing key
}

to:

if let val = toml.string("key", "path", "to", "value") {
   print(val)
}
@jdfergason
Copy link
Owner Author

@emlai I would appreciate any feedback you may have on this topic. I think this is probably useful but would like to get it in before 1.0.0 when the API get's a lot harder to change.

@emlai
Copy link
Contributor

emlai commented Aug 24, 2016

Yeah, I think this would make the API a bit more elegant to use.

I have used YamlSwift for some time (it uses optionals), and now that I have used swift-toml for some time as well, I think I like optionals more for this kind of stuff.

Although there's try? which can be used to handle throwing functions in a way very close to the version using optionals:

if let val = try? toml.string("key", "path", "to", "value") {
   print(val)
}

Also the Swift standard library uses optionals for handling situations where a requested value may not exists (e.g. Dictionary access), and since TOML is also about key-value pairs, it would make sense to be consistent with the Dictionary API, so I'm in favor of switching to optionals.

@jdfergason
Copy link
Owner Author

This is now part of the 0.4.0 release

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

2 participants