nicklockwood / SwiftFormat

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

Incorrectly considers `$foo` unused when using `foo` #1190

Closed denizdogan closed 2 years ago

denizdogan commented 2 years ago

In this example, modified from an article from Swift by Sundell: https://www.swiftbysundell.com/articles/bindable-swiftui-list-elements/

struct NoteListView: View {
    @ObservedObject var list: NoteList

    var body: some View {
        List {
            ForEach($list.notes) { $note in
                Text(note.foobar)  // notice it says `note` and not `$note` – this is intentional
            }
        }
    }
}

Running the above through SwiftFormat generates this:

struct NoteListView: View {
    @ObservedObject var list: NoteList

    var body: some View {
        List {
            ForEach($list.notes) { _ in
                Text(note.foobar)  // Cannot find 'note' in scope
            }
        }
    }
}

Unless I'm mistaken, SwiftFormat incorrectly determines that $note is unused since I only use note and not $note. There are situations where you want to use $note as the parameter but still use just note, such as this:

ForEach($vm.items) { $item in
    Button {
        item.enabled.toggle()  // this works, thanks to $item
    } label: {
        Text("\(item.name) is \(item.enabled ? "enabled" : "disabled")")
    }
}

It would not work without using $item.

Am I correct in thinking this is a bug?

nicklockwood commented 2 years ago

@denizdogan yeah, this is a bug. Thanks for reporting it.

nicklockwood commented 2 years ago

@denizdogan fixed in 0.49.10