[swift-evolution] Localization support for string interpolation

Chris Lattner clattner at apple.com
Sun Apr 24 16:40:30 CDT 2016


> On Apr 24, 2016, at 2:33 PM, Chris Lattner via swift-evolution <swift-evolution at swift.org> wrote:
> 
> 
>> On Apr 21, 2016, at 12:42 AM, Daniel Höpfl via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> Hi there!
>> 
>> TL;DR: Here’s my idea for a better localized strings handling in Swift.
>> It includes both, support for string interpolation support for
>> NSLocalizedString, and a new string delimiter `...` that can be used
>> instead of NSLocalizedString("...”).
> 
> FWIW, this is closely related to the idea of extending string interpolation to support generalized “printf” style modifiers, which would allow very expressive formatting inline in a string interpolation.  This has not yet come to pass, but a write up of the ideas are available here:
> https://github.com/apple/swift/blob/master/docs/TextFormatting.rst

Actually, it looks like the interesting point didn’t make it into the formal writeup.  The idea was to enable something like this (just a sketch):

public protocol CustomStringConvertible {
  /// A textual representation of `self`.
  var description: String { get }

  func formattedDescription(format: String) -> String { get }
}


Int could then implement support for “x” to print hexadecimal, we could support left/right whitespace padding, and custom types could provide their own custom formatters (e.g. a string could have a title case formatter, or a "look up localized form of” modifier).  We could then provide a “printf” that would allow traditional “%x0” substitutions.  It could also be incorporated into the string literal syntax by allowing something like:

	let hashValue = 42  // not a good hash function
	print(“Hashcode = \(hashValue:x)”)

This is just a sketch, but that’s the idea.  It never went anywhere because we didn’t have the language features in place to make it work, notably defaulted implementations in protocols were missing at the time.

-Chris


More information about the swift-evolution mailing list