nicklockwood / SwiftFormat

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

Enforce private properties in SwiftUI `View`'s #873

Open sindresorhus opened 3 years ago

sindresorhus commented 3 years ago

Apple recommends that state properties in SwiftUI View's are private:

You should only access a state property from inside the view’s body, or from methods called by it. For this reason, declare your state properties as private, to prevent clients of your view from accessing it. - https://developer.apple.com/documentation/swiftui/state

All of these should be marked as private:

struct ContentView: View {
    @State var foo = ""
}
struct ContentView: View {
    @ObservedObject var foo = Foo()
}
struct ContentView: View {
    @EnvironmentObject var foo
}
struct ContentView: View {
    @StateObject var foo = Foo()
}
struct ContentView: View {
    @Environment(\.colorScheme) var colorScheme
}
nicklockwood commented 3 years ago

This seems doable. It would have to be an opt-in rule since it has potential to break existing code (even if the code in question deserves to be broken).

rudyrichter commented 2 years ago

@nicklockwood this would be great, thoughts on giving it private and internal as options?