LoginSignup
11
12

More than 5 years have passed since last update.

【Swift4】(国際化対応)NSLocalizedStringをString extensionで実装する

Last updated at Posted at 2017-08-19

既に当たり前のextensionだと思いますが、備忘録として書いておきます。

下記のような感じで使用します。

print( "多言語化".localized )   // "Multilingualization"

extensionは下記の通り。

import Foundation

extension String
{
    // 多言語対応
    // 対象言語の「Localizable.strings」ファイルがない場合は、(Base)が使用されます。
    // 指定の文字列が「Localizable.strings」にない場合は、commentが採用されます。本実装では元の文字列が選択されます。
    var localized: String
    {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: self)
    }
}

NSLocalizedStringではdefaultが効いているので、ごちゃごちゃ書かないで

var localized: String
{
   return NSLocalizedString(self, comment: self)
}

で大丈夫です。

注意したいのは最初に「Localizable.strings」ファイルを作った時に「info.plist」の「Localization native development region」が「en」(英語)になっていることです。

例えば
「Localization native development region」が「en」
「Localizable.strings」のBaseを日本語
「Localizable.strings」のEnglishを(もちろん)英語
で作成すると日本語環境でもBaseの日本語はパスされて英語が表示されます。

「Localizable.strings」のBaseを英語
「Localizable.strings」のJapaneseを作成することで
日本語環境は日本語、それ以外は英語を表示することができます。

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12