genstrings with Swift

masakihori profile image hori,masaki ・1 min read

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

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")

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

genstrings -s LocalizedString LocalizedStrings.swift

4th step
use LocalizedStrings in your code.

let foo = LocalizedStrings.foo.string  // getting localized string.


Editor guide