Difference between Text("") and Text(verbatim: "") initializers in SwiftUI

Text(verbatim: ) returns text as it is - hence the verbatim argument name.

Text(:_) checks if the argument is a localized key.

If it is, it returns the corresponding localized string.

It it isn't, it will print the text verbatim.


As noted in a few of the WWDC19 sessions introducing it, SwiftUI tries to handle for you, by default, a whole bunch of good-platform-citizen behaviors that end users consider basic requirements of an app but which tend to complicate work for developers.

Localization is one of those things — Text initializers automatically do the right thing. Examples:

  • Text(“Some Text”) treats the string literal as localized, because text defined statically is just about always intended to be UI text.
  • Ditto for Text(“\(items.count) items”), which correctly localizes the format string and inserts the interpolated value.
  • Text(item.name) dynamically feeds different strings at runtime, so the text is almost certainly “content” that stays the same regardless of locale (because it’s from the user, from outside the program, etc).

This means that 99% of the time you can just make the most natural, concise calls to set up your UI, and end up with an app that’s ready for localization without you needing to go back and change a bunch of code the way you do with other UI frameworks.

And if your app has bits not fitting those assumptions, Text(verbatim:) and Text(_:tableName:bundle:comment:) let you make static text that’s non-localized and programmatic text that localizes.

Tags:

Swift

Swiftui