R.swift
R.swift copied to clipboard
Use callAsFunction to retrieve image
Accompanies https://github.com/mac-cain13/R.swift.Library/pull/40
I think there are several things we could do to reduce the generated code. For example, given a image called avatar.png, R will generate:
/// Image `image_tags_text_author_zh-Hant`.
public static let avatar = Rswift.ImageResource(bundle: R.hostingBundle, name: "avatar")
#if os(iOS) || os(tvOS)
/// `UIImage(named: "avatar", bundle: ..., traitCollection: ...)`
public static func avatar(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.avatar, compatibleWith: traitCollection)
}
#endif
The static variable was totally fine. But there is no need to generate the following method for every image, we could just implement this method once in ImageResource.
Maybe this is intended, to align the API with Android's R. If so, we could use callAsFunction to build a similar API:
extension ImageResource {
#if os(iOS) || os(tvOS)
public func callAsFunction(compatibleWith traitCollection: UITraitCollection? = nil) -> UIImage? {
UIKit.UIImage(resource: self, compatibleWith: traitCollection)
}
#endif
}
R.image.avatar(compatibleWith: nil) // call the `callAsFunction` function
Other resources could use the same way to reduce the generated code, except for string. String has intepolation. I don't know how to solve this properly, maybe just stay the old way for string with intepolation.
As a result, it would reduce the LOC from 37000+ to 9000+ for my project, faster to open, faster to build, no API breaking.
One small problem is API discoverability, this method wil not display in code-completion list like before.
Any thoughts? @mac-cain13