JerryZhou
JerryZhou

Reputation: 5196

swift set value with switch will got error: expected initial value after '='

I would wonder if there's any short cut way to set value of colorPredicate

enum Color { case black case white }

func predicateForColor(color: Color, compoundWith compoundPredicate: NSPredicate?) -> NSPredicate {

//  NOTE: if I use the code bellow to set the value of colorPredicate, will got error: expected initial value after '='.
//    let colorPredicate =
//        switch color {
//        case .black:   return predicateForBlack()
//        case .white:   return predicateForWhite()
//        }

    func getPredicateByColor(color: Color) -> NSPredicate {
        switch color {
        case .black:    return predicateForBlack()
        case .white:    return predicateForWhite()
        }
    }

    let colorPredicate = getPredicateByColor(color: color)

    if let predicate = compoundPredicate {
        return NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, colorPredicate])
    } else {
        return colorPredicate
    }
}


func predicateForBlack() -> NSPredicate {
    print("get black predicate")
    return NSPredicate(format: "color = black")
}

func predicateForWhite() -> NSPredicate {
    print("get white predicate")
    return NSPredicate(format: "color = white & someother condition")
}


print(predicateForColor(color: .black, compoundWith: nil))

Upvotes: 1

Views: 2552

Answers (1)

simonWasHere
simonWasHere

Reputation: 1340

let colorPredicate: NSPredicate = { (color: Color) -> NSPredicate in
    switch color {
        case .black:   return predicateForBlack()
        case .white:   return predicateForWhite()
    }
}(color)

update

Your code produces an error because you need to write:

let variable = { switch { ... } }()

instead of

let variable = switch { ... }

so that you define a block and call it, you cannot assign from a switch statement.

dictionary approach

setup:

var lookup: [Color: NSPredicate] = [:]
lookup[.black] = NSPredicate(format: "color = black")
lookup[.white] = NSPredicate(format: "color = white")

use:

let colorPredicate = lookup[color]

Upvotes: 1

Related Questions