R.swift
Strong typed, autocompleted resources like images, fonts and segues in Swift projects
Top Related Projects
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!
✨ Super sweet syntactic sugar for Swift initializers
A lightweight, pure-Swift library for downloading and caching images from the web.
Network abstraction layer written in Swift.
Quick Overview
R.swift is a tool for iOS developers that generates a strong-typed resource class for all resources in your Xcode project. It provides compile-time checked resources, eliminating runtime errors and improving code completion for image names, fonts, and other assets.
Pros
- Compile-time safety for resource usage, reducing runtime errors
- Improved code completion and autocorrect for resource names
- Easier refactoring and renaming of resources
- Supports various resource types including images, fonts, colors, and localized strings
Cons
- Requires integration into the build process, which can be complex for some projects
- May increase build times, especially for large projects
- Learning curve for developers unfamiliar with code generation tools
- Occasional conflicts with other build scripts or tools
Code Examples
- Accessing an image:
let icon = R.image.settingsIcon()
- Using a localized string:
let welcomeMessage = R.string.localizable.welcomeMessage()
- Accessing a custom font:
let customFont = R.font.nunitoRegular(size: 16)
- Using a color from asset catalog:
let primaryColor = R.color.primaryColor()
Getting Started
- Install R.swift using CocoaPods by adding to your Podfile:
pod 'R.swift'
-
Run
pod install
in your terminal. -
Add a new "Run Script Phase" to your target's "Build Phases":
"$PODS_ROOT/R.swift/rswift" generate "$SRCROOT/R.generated.swift"
-
Add the generated file to your Xcode project.
-
Import and use R.swift in your code:
import Rswift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let image = R.image.logo()
let label = UILabel()
label.text = R.string.localizable.welcome()
label.font = R.font.nunitoBold(size: 18)
}
}
Competitor Comparisons
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!
Pros of SwiftGen
- Supports a wider range of resource types, including JSON, YAML, and Plist files
- Offers more customization options through templates
- Provides better support for localization and multi-platform projects
Cons of SwiftGen
- Slightly more complex setup and configuration process
- May require more maintenance due to its broader feature set
- Can be slower for large projects due to its comprehensive code generation
Code Comparison
R.swift:
let image = R.image.backgroundImage()
let color = R.color.primaryColor()
let string = R.string.localizable.welcomeMessage()
SwiftGen:
let image = Asset.backgroundImage.image
let color = Asset.Colors.primaryColor.color
let string = L10n.Welcome.message
Both tools generate type-safe accessors for resources, but SwiftGen's output is more customizable through templates. R.swift tends to use a more uniform naming convention, while SwiftGen's output can be tailored to fit specific project needs.
SwiftGen offers more flexibility in handling various resource types and supports more complex project structures. However, R.swift provides a simpler, more straightforward approach that may be sufficient for many projects.
Ultimately, the choice between these tools depends on the project's specific requirements, team preferences, and the desired level of customization in resource management.
✨ Super sweet syntactic sugar for Swift initializers
Pros of Then
- Simplifies object initialization and configuration in Swift
- Lightweight and easy to integrate into existing projects
- Supports both class and struct initialization
Cons of Then
- Limited to object initialization, unlike R.swift's broader scope
- Doesn't provide type-safe access to resources like R.swift does
- May encourage overuse of complex initializers
Code Comparison
Then:
let label = UILabel().then {
$0.textAlignment = .center
$0.textColor = .black
$0.text = "Hello, World!"
}
R.swift:
let image = R.image.settingsIcon()
let color = R.color.brandPrimary()
let font = R.font.helveticaNeue(size: 16)
Key Differences
- Then focuses on simplifying object initialization and configuration
- R.swift provides type-safe access to various project resources
- R.swift generates a centralized
R
struct for accessing resources - Then uses a closure-based approach for object configuration
Use Cases
- Use Then for cleaner and more concise object initialization
- Use R.swift for type-safe access to project resources and avoiding "stringly-typed" code
Integration
- Then is a simple drop-in library with minimal setup
- R.swift requires a build script and generates code based on project resources
Community and Maintenance
- Both projects are open-source and actively maintained
- R.swift has a larger community and more frequent updates
A lightweight, pure-Swift library for downloading and caching images from the web.
Pros of Kingfisher
- Specialized for image downloading and caching
- Extensive features for image processing and manipulation
- Active development and community support
Cons of Kingfisher
- Limited to image-related tasks
- May be overkill for projects with simple image needs
- Steeper learning curve due to more complex API
Code Comparison
Kingfisher:
let url = URL(string: "https://example.com/image.png")
imageView.kf.setImage(with: url)
R.swift:
imageView.image = R.image.myImage()
Key Differences
R.swift focuses on generating type-safe accessors for resources, while Kingfisher specializes in image downloading and caching. R.swift provides a broader scope for resource management, including strings, colors, and fonts, whereas Kingfisher offers advanced image processing capabilities.
R.swift is ideal for projects requiring strong typing and compile-time checks for various resources. Kingfisher excels in applications with heavy image loading and manipulation needs, especially when dealing with remote images.
Both libraries enhance iOS development, but they serve different primary purposes. R.swift improves overall resource management and type safety, while Kingfisher optimizes image handling workflows.
Network abstraction layer written in Swift.
Pros of Moya
- Provides a higher level of abstraction for network requests, simplifying API integration
- Offers built-in support for testing and stubbing network calls
- Includes features like plugins and reactive extensions for enhanced functionality
Cons of Moya
- Steeper learning curve due to its more complex architecture
- May introduce unnecessary overhead for simpler projects
- Requires additional setup and configuration compared to R.swift
Code Comparison
R.swift example:
let image = R.image.backgroundImage()
let font = R.font.helveticaNeue(size: 16)
let color = R.color.mainColor()
Moya example:
let provider = MoyaProvider<MyAPI>()
provider.request(.userProfile) { result in
switch result {
case let .success(response):
let data = response.data
// Handle the response
case let .failure(error):
// Handle the error
}
}
While R.swift focuses on type-safe access to resources, Moya provides a structured approach to network requests. R.swift is simpler to integrate and use, especially for resource management, while Moya offers more comprehensive networking features but requires more setup. The choice between them depends on the project's specific needs and complexity.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
R.swift
Get strong typed, autocompleted resources like images, fonts and segues in Swift projects
Why use this?
It makes your code that uses resources:
- Fully typed, less casting and guessing what a method will return
- Compile time checked, no more incorrect strings that make your app crash at runtime
- Autocompleted, never have to guess that image name again
Currently you type:
let icon = UIImage(named: "settings-icon")
let font = UIFont(name: "San Francisco", size: 42)
let color = UIColor(named: "indicator highlight")
let viewController = CustomViewController(nibName: "CustomView", bundle: nil)
let string = String(format: NSLocalizedString("welcome.withName", comment: ""), locale: NSLocale.current, "Arthur Dent")
With R.swift it 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")
Check out more examples or hear about how Fabric.app uses R.swift!
Demo
Autocompleted images:
Compiletime checked images:
This is only the beginning, check out more examples!
CocoaHeadsNL presentation
Mathijs Kadijk presented R.swift at the September 2016 CocoaHeadsNL meetup. Talking about the ideas behind R.swift and demonstrating how to move from plain stringly-typed iOS code to statically typed code.
Features
After installing R.swift into your project you can use the R
-struct to access resources. If the struct is outdated just build and R.swift will correct any missing/changed/added resources.
R.swift currently supports these types of resources:
Runtime validation with R.validate()
:
- If all images used in storyboards and nibs are available
- If all named colors used in storyboards and nibs are available
- If all view controllers with storyboard identifiers can be loaded
- If all custom fonts can be loaded
Q&A
- Why was R.swift created?
- Why should I choose R.swift over alternative X or Y?
- What are the requirements to run R.swift?
- How to use methods with a
Void
argument? - How to fix missing imports in the generated file?
- How to use classes with the same name as their module?
- Can I ignore resources?
- Can I use R.swift in a library?
- How does R.swift work?
- How to upgrade to a new major version?
- How can I only run specific generators?
Installation
As of Rswift 7, Swift Package Manager is the recommended method of installation.
Demo video: Updating from R.swift 6 to Rswift 7 (Starting at 1:06, this describes the installation of Rswift 7).
Xcode project - SPM
- In Project Settings, on the tab "Package Dependencies", click "+" and add
github.com/mac-cain13/R.swift
- Select your target, on the tab "General", in the section "Frameworks, Libraries, and Embeded Content", click "+" and add
RswiftLibrary
- Select your target, on the tab "Build Phases", in the section "Run Build Tool Plug-ins", click "+" and add
RswiftGenerateInternalResources
- Build your project, now the
R
struct should be available in your code, use auto-complete to explore all static references
Screenshot of the Build Phase can be found here
When running on Xcode Cloud
- Add a custom build script in
ci_scripts/ci_post_clone.sh
with the content:defaults write com.apple.dt.Xcode IDESkipPackagePluginFingerprintValidatation -bool YES
Package.swift based SPM project
- Add a dependency in Package.swift:
dependencies: [ .package(url: "https://github.com/mac-cain13/R.swift.git", from: "7.0.0") ]
- For each relevant target, add a dependency and a plugin
.target( name: "Example", dependencies: [.product(name: "RswiftLibrary", package: "R.swift")], plugins: [.plugin(name: "RswiftGeneratePublicResources", package: "R.swift")] )
- Build your project, now the
R
struct should be available in your code, use auto-complete to explore all static references
CocoaPods
- Add
pod 'R.swift'
to your Podfile and runpod install
- In Xcode: Click on your project in the file list, choose your target under
TARGETS
, click theBuild Phases
tab and add aNew Run Script Phase
by clicking the little plus icon in the top left - Drag the new
Run Script
phase above theCompile Sources
phase and belowCheck Pods Manifest.lock
, expand it and paste the following script:"$PODS_ROOT/R.swift/rswift" generate "$SRCROOT/R.generated.swift"
- Add
$SRCROOT/R.generated.swift
to the "Output Files" of the Build Phase - Uncheck "Based on dependency analysis" so that R.swift is run on each build
- Build your project, in Finder you will now see a
R.generated.swift
in the$SRCROOT
-folder, drag theR.generated.swift
files into your project and uncheckCopy items if needed
Screenshot of the Build Phase can be found here
Tip: Add the *.generated.swift
pattern to your .gitignore
file to prevent unnecessary conflicts.
Mint
- Add the R.swift library to your project
- Add
mac-cain13/R.swift
to your Mintfile and runmint bootstrap
to install this package without linking it globally (recommended) - In Xcode: Click on your project in the file list, choose your target under
TARGETS
, click theBuild Phases
tab and add aNew Run Script Phase
by clicking the little plus icon in the top left - Drag the new
Run Script
phase above theCompile Sources
phase, expand it and paste the following script:if mint list | grep -q 'R.swift'; then mint run R.swift@v7.0.1 rswift generate "$SRCROOT/R.generated.swift" else echo "error: R.swift not installed; run 'mint bootstrap' to install" return -1 fi
- Add
$SRCROOT/R.generated.swift
to the "Output Files" of the Build Phase - Uncheck "Based on dependency analysis" so that R.swift is run on each build
- Build your project, in Finder you will now see a
R.generated.swift
in the$SRCROOT
-folder, drag theR.generated.swift
files into your project and uncheckCopy items if needed
Tip: Add the *.generated.swift
pattern to your .gitignore
file to prevent unnecessary conflicts.
Homebrew
R.swift is also available through Homebrew. This makes it possible to install R.swift globally on your system. Install R.swift by running: brew install rswift
. The Homebrew formula is maintained by @tomasharkema.
Manually
- Add the R.swift library to your project
- Download a R.swift release, unzip it and put it into your source root directory
- In Xcode: Click on your project in the file list, choose your target under
TARGETS
, click theBuild Phases
tab and add aNew Run Script Phase
by clicking the little plus icon in the top left - Drag the new
Run Script
phase above theCompile Sources
phase, expand it and paste the following script:"$SRCROOT/rswift" generate "$SRCROOT/R.generated.swift"
- Add
$SRCROOT/R.generated.swift
to the "Output Files" of the Build Phase - Uncheck "Based on dependency analysis" so that R.swift is run on each build
- Build your project, in Finder you will now see a
R.generated.swift
in the$SRCROOT
-folder, drag theR.generated.swift
files into your project and uncheckCopy items if needed
Screenshot of the Build Phase can be found here
Tip: Add the *.generated.swift
pattern to your .gitignore
file to prevent unnecessary conflicts.
Contribute
We'll love contributions, read the contribute docs for info on how to report issues, submit ideas and submit pull requests!
License
R.swift and R.swift.Library are created by Mathijs Kadijk and released under a MIT License.
Special thanks to Tom Lokhorst for his major contributions and help maintaining this project.
Top Related Projects
The Swift code generator for your assets, storyboards, Localizable.strings, … — Get rid of all String-based APIs!
✨ Super sweet syntactic sugar for Swift initializers
A lightweight, pure-Swift library for downloading and caching images from the web.
Network abstraction layer written in Swift.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot