Xcode 15 offers a new really cool feature.

The ability to generate assets symbols automatically without any third-party library like R.swift or SwiftGen.

So, colors and images resources are now generated by Xcode without any additional work.

This is really handy since it avoids typos and crashes due to force-unwrap a resource.

Let’s see how it works.

Color resources

First, we need to add colours as we normally would to the assets folder (e.g. Assets.xcassets), let’s say we add the light.red color. Then, to access the generated resource:

// SwiftUI

Color(.lightRed)

// UIKit

UIColor(resource: .lightRed)

// AppKit

NSColor(resource: .lightRed)

Image resources

The same concept applies for images too.

So, if we add the apple_logo image, we will access this way:

/// SwiftUI

Image(.appleLogo)

/// UIKit

UIImage(resource: .appleLogo)

/// AppKit

NSImage(resource: .appleLogo)

Generate Asset Symbols Options

Disable automatic generation

The resources generation is enabled by default, if you want to disable it, you can go to Build Settings and set Generate Asset Symbols to false.

Asset symbol framework support

To choose to generate resources only for a subset of frameworks go to Build Settings and set Generate Swift Asset Symbol Framework Support to the desired set of frameworks. e.g. “UIKit AppKit” or “AppKit”.

Asset symbol extensions

You can access the color or image also as an extension of its type, eg. Color.lightRed or Image.appleLogo, for SwiftUI. This is enabled by default. If you want to disable it, go to Build Settings and set the Generate Swift Asset Symbol Extensions to false.

What are you thoughts about this? Tweet me @franceleonidev and share your opinion.

Source link