How do I use resources and localization in SPM targets?

In Swift Package Manager (SPM), you can include resources and use localization features easily. Here's how to do it effectively:

Step 1: Organize Your Resources

To add resources to your SPM target, create a directory structure in your package as follows:


    MyPackage/
    ├── Sources/
    │   └── MyLibrary/
    │       └── MyCode.swift
    ├── Resources/
    │   ├── en.lproj/
    │   │   └── Localizable.strings
    │   └── es.lproj/
    │       └── Localizable.strings
    └── Package.swift
    

Step 2: Edit Your Package.swift

Make sure to declare resources in your target within the Package.swift file:


    import PackageDescription

    let package = Package(
        name: "MyPackage",
        products: [
            .library(name: "MyLibrary", targets: ["MyLibrary"]),
        ],
        targets: [
            .target(
                name: "MyLibrary",
                resources: [
                    .process("Resources")
                ]
            ),
        ]
    )
    

Step 3: Access Localized Strings

In your Swift code, you can access localized strings using the following approach:


    import Foundation

    struct LocalizedStrings {
        static let helloWorld = NSLocalizedString("hello_world", comment: "Hello World greeting")
    }
    

Swift Package Manager SPM localization resources Swift iOS development