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

2

16

I've been following Apple's SwiftUI tutorials. Along the way, I've often used the Text object with the following initializer:

/// Creates an instance that displays `content` verbatim.
public init<S>(_ content: S) where S : StringProtocol

Now, in the fifth tutorial of the series, I've encountered the following usage of Text:

Text(verbatim: "")

The description in the interface is the same as for the other initializer:

/// Creates an instance that displays `content` verbatim.
public init(verbatim content: String)

Question

What's the two initializers for and how are they different / when would I use which?

Esperance answered 8/6, 2019 at 10:52 Comment(0)
A
26

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.

Aquiver answered 8/6, 2019 at 11:8 Comment(2)
Interesting finding! How does it try to localize it? Does it just search any localizable.strings files for the key?Esperance
@Esperance yes, it checks the current locale and the fetches the corresponding Localizable.strings file.Aquiver
A
8

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.

Algophobia answered 14/6, 2019 at 6:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.