将 switch case 语句转换为 Swift 中的值

Ho *_*uan 1 enums case switch-statement swift

也许这是一个愚蠢的问题

我有一个这样的 switch case 语句:

        self.text = type.rawValue
        switch type {
        case .teuro:
            self.backgroundColor =  UIColor.sapphireColor()
        case .lesson:
            self.backgroundColor = UIColor.orangeColor()
        case .profession:
            self.backgroundColor = UIColor.pinkyPurpleColor()
        }
Run Code Online (Sandbox Code Playgroud)

有什么办法可以将其写成类似以下示例的内容:

        self.backgroundColor = {
            switch type {
            case .teuro:
                return  UIColor.sapphireColor()
            case .lesson:
                return  UIColor.orangeColor()
            case .profession:
                return UIColor.pinkyPurpleColor()
            }
        }
Run Code Online (Sandbox Code Playgroud)

任何评论或回答表示赞赏。谢谢。

Swe*_*per 5

你快到了!

您已经创建了一个返回颜色的闭包,并将其分配给一个UIColor属性,但闭包不是颜色!

您只需要调用(调用)闭包来运行它,以便它返回您想要的颜色:

self.backgroundColor = {
    switch type {
    case .teuro:
        return  UIColor.sapphireColor()
    case .lesson:
        return  UIColor.orangeColor()
    case .profession:
        return UIColor.pinkyPurpleColor()
    }
}() // <---- notice the brackets!
Run Code Online (Sandbox Code Playgroud)