realm/SwiftLint

Rule Request: SwiftUI: Prefer scaledToFit()/scaledToFill() over aspectRatio(contentMode:)

Open

#5,713 opened on Jul 29, 2024

View on GitHub
 (4 comments) (3 reactions) (1 assignee)Swift (19,570 stars) (2,295 forks)batch import
good first issuerule-request

Description

New Issue Checklist

New rule request

SwiftUI has scaledToFit() scaledToFill() which are convenience methods for calling aspectRatio with only a content mode.

This method is equivalent to calling aspectRatio(_:contentMode:) with a nil aspectRatio and a content mode of ContentMode.fit. https://developer.apple.com/documentation/swiftui/view/scaledtofit()#

Since Apple considered it a common enough use case to have dedicated view modifiers for it, there should be a rule to prefer using them over the more general purpose view modifier.

Triggering cases

It just needs to be the versions where they're passed a constant.

view.aspectRatio(contentMode: .fit)
view.aspectRatio(contentMode: .fill)

aspectRatio(contentMode: .fit)
aspectRatio(contentMode: .fill)

Non-triggering cases

If a ratio is being passed or the content mode is not a constant, it should not trigger

let ratio = CGSize(width: 1, height: 1)
view.aspectRatio(ratio, contentMode: .fit)
view.aspectRatio(ratio, contentMode: .fill)

let contentMode = ContentMode.fit
view.aspectRatio(contentMode: contentMode)

let shouldFit = true
view.aspectRatio(contentMode: shouldFit ? .fit : .fill)

Configuration

I don't think this needs any configuration.

It's always possible someone else would prefer the aspectRatio method over the convenience method. If that occurs the rule could be modified to controlling the preferred method, though it could also be a separate rule as well since it would be checking for the opposite case.

Opt-in?

Based on the criteria in the readme, this could be enabled by default. Though it depends on what the general consensus is.

Contributor guide