jdfergason/swift-toml

How to iterate through all tables?

Closed this issue · 4 comments

emlai commented

I have a use case where I would need to loop over all root-level tables to check whether each table contains a certain key. Currently this doesn't seem to be possible.

I was previously using YamlSwift, where this was possible using the dictionary getter:

for (key, value) in yaml.dictionary! {
    if let property = value["property"] {
        // use `key` and `property`
    }
}

It would be nice to have something similar in swift-toml, for example:

for (tableName, table) in toml.tables {
    if let property = try? table.double("property") {
        // use `tableName` and `property`
    }
}

I can see the use for this but it's not so straightforward to implement since swift-toml is basically storing key/values in a flat structure after it's parsed. I'm working on a function that will allow you to grab all tables beneath a given key path.

To grab all tables at the root level:

for (tableName, table) in toml.tables() { ... }

or, to get all the tables nested within table1:

for (tableName, table) in toml.tables("table1") { ... } 

It will take me a day or two to get this functionality in.

emlai commented

Awesome!

Added support for iterating over all tables at a given level with tables(_: [String]) method in 85fc130 and created v0.3.0 release.

emlai commented

Nice, thanks!