Clicky

iOS Dev Nugget 281 Use R.swift for Static References to Resources Like Images

.

Need to run a code review on your codebase? Hire me

Swift is a strongly typed language, so it makes sense when using it to tweak your tools and code to take advantage of type-checking. This week's nugget goes along that line.

The library R.swift automatically generates static references to resources such as font files and image files so that you don't have to refer to them by string. Example from the README:

let icon = UIImage(named: "settings-icon")
let font = UIFont(name: "San Francisco", size: 42)
let color = UIColor(named: "indictator highlight")
let viewController = CustomViewController(nibName: "CustomView", bundle: nil)
let string = String(format: NSLocalizedString("welcome.withName", comment: ""), locale: NSLocale.current, "Arthur Dent")

becomes:

let icon = R.image.settingsIcon()
let font = R.font.sanFrancisco(size: 42)
let color = R.color.indicatorHighlight()
let viewController = CustomViewController(nib: R.nib.customView)
let string = R.string.localizable.welcomeWithName("Arthur Dent")

This avoids the chance of typing a string wrongly and not catching it before submitting a build to the app store.

Installation is simple:

  1. Include the pod (R.swift)
  2. Add a Run Script phase before Compile Sources: "$PODS_ROOT/R.swift/rswift" generate "$SRCROOT"
  3. Add the R.generated.swift file to your project

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues