i’m creating application unlimited amount of rules applied unlimited amount of nodes.
i'm planning on using core data datastore , creating simple 1 many relationship between node , rule.
in objective-c create classes each of rules , have them conform protocol.
nsarray *ruleclassnames = @[@"simplerulea",@"simpleruleb",@"bigfatcomplicatedrule"]; int ruletype = [somenode.rules firstobject]; class class = nsclassfromstring(ruleclassnames[ruletype]); [(ruleclassprotocol*)class performselector:@selector(runruleonnode:) withobject:somenode]; what elegant way of doing in swift?
solution
if want add closure enum first of lets define type of closure.
typealias logic = () -> (string) then enum:
enum rule { case simplerulea(logic) case simpleruleb(logic) case bigfatcomplicatedrule(logic) } that's it! let's see how use this.
usage
let's create couple of logic(s):
let logic0 : logic = { return "logic 0" } let logic1 : logic = { return "logic 1" } and function process rule
func processrule(rule:rule) -> string { switch rule { case .simplerulea(let logic): return "simple rule a, logic: \(logic())" case .simpleruleb(let logic): return "simple rule b, logic: \(logic())" case .bigfatcomplicatedrule(let logic): return "big fat complicated rule, logic: \(logic())" } } finally let's combine every possible rule every possible logic...
let awithlogic0 = rule.simplerulea(logic0) let awithlogic1 = rule.simplerulea(logic1) let bwithlogic0 = rule.simpleruleb(logic0) let bwithlogic1 = rule.simpleruleb(logic1) let fatwithlogic0 = rule.bigfatcomplicatedrule(logic0) let fatwithlogic1 = rule.bigfatcomplicatedrule(logic1) ... , let's test it
processrule(awithlogic0) // "simple rule a, logic: logic 0" processrule(awithlogic1) // "simple rule a, logic: logic 1" processrule(bwithlogic0) // "simple rule b, logic: logic 0" processrule(bwithlogic1) // "simple rule b, logic: logic 1" processrule(fatwithlogic0) // "big fat complicated rule, logic: logic 0" processrule(fatwithlogic1) // "big fat complicated rule, logic: logic 1" is solution close had in mind?
Comments
Post a Comment