How to assign the value of a switch statement to a variable

You can reduce the redundancy even more by using a ResultBuilder:

let ratingView: NSView = eval {
    switch rating {
    case .zero:
        self.ratingBox.zeroDot
    case .one:
        self.ratingBox.oneStar
    case .two:
        self.ratingBox.twoStar
    case .three:
        self.ratingBox.threeStar
    case .four:
        self.ratingBox.fourStar
    case .five:
        self.ratingBox.fiveStar
    }
}

Doesn't work with dot-syntax unfortunately.

Implementation
func eval<V>(@SingleValueBuilder<V> _ value: () -> V) -> V {
    value()
}

@resultBuilder
enum SingleValueBuilder<V> {
    static func buildEither(first component: V) -> V {
        component
    }
    static func buildEither(second component: V) -> V {
        component
    }
    static func buildBlock(_ components: V) -> V {
        components
    }
}

12 Likes