DEV Community

hori,masaki
hori,masaki

Posted on

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

Top comments (0)