loretoparisi
loretoparisi

Reputation: 16281

How to Declare a typed Dictionary of Dictionaries in Swift?

I have a Swift.Dictionary structure like

let tests:[ [String:Any] ] = [
            [ "f" : test1, "on" : true ],
            [ "f" : test2, "on" : false ],
            [ "f" : test3, "on" : false ],
            [ "f" : test4, "on" : false ],
            [ "f" : test5, "on" : false ]
        ]

where f is a closure of type ()->() and on is a Bool. I'm using this to enumerate and eval the closure based on the on value:

for (_, test) in tests.enumerate() {
        if test["on"] as! Bool {
            let f:()->()=test["f"] as! ()->();
            f();
        }
    }

How to explicitly declare this Swift.Dictionary structure in order to avoid to unwrap and to force convert with as!:

let f:()->()=test["f"] as! ()->();

Upvotes: 1

Views: 84

Answers (2)

brimstone
brimstone

Reputation: 3400

Does this work? Also it looks a lot cleaner.

typealias MyClosure = (() -> ())
typealias MyTuple = (f: MyClosure, on: Bool)

let tests: [MyTuple] = [ etc...

for item in tests {
    if item.on {
        let f = item.f
        f()
    }
}

Upvotes: 3

matt
matt

Reputation: 535192

This is a very inappropriate use of a dictionary. Make an array of tuples, or even an array of a lightweight struct devised for just this purpose, i.e. to carry a closure-Bool pair.

Upvotes: 3

Related Questions