Guide to Naming SwiftUI Components
Learn to name SwiftUI components effectively by replacing 'View' with root view names. Enhance code readability with this simple guide.
Whilst making Clean Share (app for removing tracking identifiers) I came across many instances where I was appending View
to the end of my SwiftUI component names. Have you also gotten into the habit of ending your component names with View
? Follow these steps to give your components better descriptive names.
Look at the root view in your
body
i.e.Image
,Text
,Label
,Button
,List
etc.Replace your component's
View
suffix with that root view name.
Some examples below could be achieved by using …Style
, however these examples are purposely kept brief and the idea still applies as your components grow beyond the capability of …Style
.
Examples
The following design is taken as inspiration.
// ✅ TransactionCategoryImage instead of...
struct TransactionCategoryView: View {
let image: String
var body: some View {
Image(image)
.resizable()
.frame(width: 20, height: 20)
}
}
// ✅ TransactionDescriptionText instead of...
struct TransactionDescriptionView: View {
let description: String
var body: some View {
Text(description)
.font(.caption2)
.foregroundStyle(.primary)
}
}
// ✅ TransactionCostLabel instead of...
struct TransactionCostView: View {
let amount: Double
var body: some View {
Label(String(describing: amount), systemImage: "dollarsign")
.font(.caption)
.foregroundStyle(.secondary)
}
}
// ✅ TransactionButton instead of...
struct TransactionView: View {
let transaction: Transaction
let action: () -> Void
var body: some View {
Button(action: action) {
HStack {
TransactionCategoryImage(image: transaction.image)
TransactionDescriptionText(description: transaction.description)
TransactionCostLabel(amount: transaction.amount)
}
}
}
}
// ✅ TransactionsList instead of...
struct TransactionsView: View {
let transactions: [Transaction]
var body: some View {
List(transactions) { transaction in
TransactionButton(transaction: transaction) { }
}
.listStyle(.plain)
}
}
Conclusion
If you're finding too many instances of components named with View
in your code just like I did in Clean Share, this tip may be for you.