Localization playing nicely with string interpolation in Swift

I can’t work out why Apple’s documentation of Swift core data types is still so poor, but luckily we have Swiftdoc. To illustrate, according to Apple docs there are two init methods for String. If you want to know the true state of affairs, look at swiftdoc, where there are about 40 varieties. Sure, a lot of them are bridged from Foundation’s NSString, but they’re still worth having info on. Or are they redundant now?

For example:

init(format: String, locale: NSLocale?, arguments: [CVarArgType])

To jog the memory banks, this may be more familiar in Objective C:

NSString *name = "Craig";
NSString *msg = [NSString stringWithFormat:@"Hello %@",name];

That old chestnut! Inserting a variable value into a string – otherwise known as string interpolation. But what do we want with that in Swift? We already have a neat much more readable new syntax for that:

let name = "Craig"
let msg = "Hello \(name)"

Well, that seems to be that. No need for the old-school Objective C interpolation if we’re programming in Swift right?

wrong…

%@ raises its ugly head in localization!

In your localization.strings files the only way of including string interpolation is still the old Objective C style. And it makes sense too, the new Swift approach includes the variable name itself in the string – that wouldn’t be possible in the localization files.

If you’re not familiar with localization there’s a great tutorial here.

So if your localization.strings file included:

"Hello %@" = "Hello %@";

The old Objective C way of accessing it was:

NSString *name = "Craig";
NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"Hello %@", nil),name];

The Swift version looks like:

let name = "Craig"
let msg = String(format: NSLocalizedString("Hello %@", comment: ""), name)

iOS development with Swift - book: https://manning.com/books/ios-development-with-swift video course: https://www.manning.com/livevideo/ios-development-with-swift-lv

Tagged with: ,
Posted in Objective C, Swift

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: