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! ()->();
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, ie to carry a closure-Bool pair.
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()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.