Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule Idea: Prefer Color/ImageResource over 'named' Initialisers #1634

Open
Sherlouk opened this issue Feb 24, 2024 · 0 comments
Open

Rule Idea: Prefer Color/ImageResource over 'named' Initialisers #1634

Sherlouk opened this issue Feb 24, 2024 · 0 comments

Comments

@Sherlouk
Copy link
Contributor

Sherlouk commented Feb 24, 2024

Description

Introduced in Xcode 15, Apple now provides type-safe access to Color and Image assets. This is done with a compile-time extension providing properties for all available assets. These can be access using new initialisers on Color and Image types (in UIKit, SwiftUI, and AppKit).

Given the enhancements this provides to safety (ensuring codebases only reference resources which actually exist), I think it would be a good rule to have in most codebases to use these new extensions -- thus having it available in this tool would be beneficial.

Examples

// Preferred
Image(.someImage)
UIImage(resource: .someImage)
Color(.someColor)

// Discouraged
UIImage(named: "someImage")
UIColor(named: "someColor", in: Bundle(for: self), compatibleWith: nil)
Image("someImage", bundle: .module)

Non Triggering Examples

This rule becomes slightly more complicated when you take into account non-static strings (where the named value is either a variable, or a string containing an interpolated variable).

// Non Triggering
UIImage("flag/\(countryCode)")

let someStringFromViewModel = model.imageName
Color(someStringFromViewModel)

// Triggering
Color(isDarkMode ? "textDark" : "textLight")

Logic

It's worth noting the property name generated by Xcode is not 100% the same as the asset name (used in the named variable). Some known examples:

  • Camel Case: some_blue = someBlue
  • Trim Color from End: someBlueColor = someBlue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants