nicklockwood / SwiftFormat

A command-line tool and Xcode Extension for formatting Swift code
MIT License
7.77k stars 629 forks source link

Compiler error with 5.9 conversion to switch expression #1544

Closed drekka closed 8 months ago

drekka commented 10 months ago

With this code:

var productListInteractionType: ProductListInteractionType
    switch type {
    case .brandClick:
        productListInteractionType = .brand
        onBrandSelection(product)
    case .addToWishlist:
        productListInteractionType = .addToWishlist
        addToWishlist(product)
}

SwiftFormat incorrect refactors it to be:

var productListInteractionType: ProductListInteractionType = switch type {
    case .brandClick:
        .brand
        onBrandSelection(product)
    case .addToWishlist:
        .addToWishlist
        addToWishlist(product)
}

Which raises a number of errors. However if I refactor to put the function calls before the assignments like this:

var productListInteractionType: ProductListInteractionType
    switch type {
    case .brandClick:
        onBrandSelection(product)
        productListInteractionType = .brand
    case .addToWishlist:
        addToWishlist(product)
        productListInteractionType = .addToWishlist
}

Then Swiftformat correctly ignores the switch, leaving the code as it was.

It would appear that SwiftFormat is only looking at the first statement within each case and if it is an assign then reformatting the whole switch into a switch expression. If this is correct then the rule should probably first look at the number of statements within each case and if any are > 1 exit the rule.

nicklockwood commented 10 months ago

@drekka I'm not able to reproduce this with SwiftFormat 0.52.7 - is it possible it's fixed already?