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

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

我想知道是否有任何快捷方式来设置 colorPredicate

的值

枚举颜色{ 黑色外壳 外壳白色 }

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))
let colorPredicate: NSPredicate = { (color: Color) -> NSPredicate in
    switch color {
        case .black:   return predicateForBlack()
        case .white:   return predicateForWhite()
    }
}(color)

更新

您的代码产生错误,因为您需要编写:

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

而不是

let variable = switch { ... }

这样你就可以定义一个块并调用它,你不能从 switch 语句中赋值。

字典方法

设置:

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

使用:

let colorPredicate = lookup[color]