Search code examples
iosswiftlocalizationnslocalizedstring

What's NSLocalizedString equivalent in Swift?


Is there an Swift equivalent of NSLocalizedString(...)? In Objective-C, we usually use:

NSString *string = NSLocalizedString(@"key", @"comment");

How can I achieve the same in Swift? I found a function:

func NSLocalizedString(
    key: String,
    tableName: String? = default,
    bundle: NSBundle = default,
    value: String = default,
    #comment: String) -> String

However, it is very long and not convenient at all.


Solution

  • The NSLocalizedString exists also in the Swift's world.

    func NSLocalizedString(
        key: String,
        tableName: String? = default,
        bundle: NSBundle = default,
        value: String = default,
        #comment: String) -> String
    

    The tableName, bundle, and value parameters are marked with a default keyword which means we can omit these parameters while calling the function. In this case, their default values will be used.

    This leads to a conclusion that the method call can be simplified to:

    NSLocalizedString("key", comment: "comment")
    

    Swift 5 - no change, still works like that.