DEV Community

hori,masaki
hori,masaki

Posted on

2 1

genstrings with Swift

1st step
Localizable protocol in Localizable.swft

import Foundation

protocol Localizable {

    var key: String { get }
    var bundle: Bundle { get }
    var comment: String { get }

    var string: String { get }
}

extension Localizable {

    var string: String {

        return NSLocalizedString(key, tableName: nil, bundle: bundle, comment: comment)
    }
}

struct LocalizedString: Localizable {

    let key: String
    let bundle: Bundle = .main
    let comment: String


    init(_ string: String, comment: String) {
        self.key = string
        self.comment = comment
    }
}
Enter fullscreen mode Exit fullscreen mode

2nd step
LocalizedStrings struct in LocalizedStrings.swift.

this file is actual Localize settings.

struct LocalizedStrings {

    static let hoge = LocalizedString("Hoge", comment: "Hoge Comment")
    static let foo = LocalizedString("Foo", comment: "Foo Comment")
}
Enter fullscreen mode Exit fullscreen mode

3rd step
run genstrings with 's'option to 'LocalizedStrings.swift'

genstrings -s LocalizedString LocalizedStrings.swift
Enter fullscreen mode Exit fullscreen mode

4th step
use LocalizedStrings in your code.

let foo = LocalizedStrings.foo.string  // getting localized string.
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay