Difference Between Text("") and Text(Verbatim: "") Initializers in Swiftui

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.

Prevent Text( string ) from being exported as localization

Use with verbatim constructor, like

Text(verbatim: "dummy")

String Inference Protocol For Generic SwiftUI View

This depends on whether you're trying to display the passed value, or you're trying trying to display the localized string for the passed key. It looks like you're trying to display the passed value, but your code is calling the initializer for a localization key. You likely want to use Text(verbatim:):

struct GenericTextView<A>: View {
var printableInstance: A

var body: some View {
Text(verbatim: "\(printableInstance)")
}
}

That said, I'd avoid writing it that way. There's no reason to re-stringify the value this way. You can just stringify it one time and avoid the generic:

struct GenericTextView: View {
var string: String

init<Value>(_ value: Value) {
string = "\(value)"
}

var body: some View {
Text(verbatim: string)
}
}

This approach also allows localization keys, just by dropping the verbatim:.

Cannot use custom view in SwiftUI

You need to add string: to your Title() initializer:

var body: some View {
VStack(alignment: .leading) {
Title(string: "Welcome")
Title(string: "to SwiftUI")
}
}

Compiler errors are currently misleading and not located near where the real issue is.

Going crazy with UserDefaults in Swift[UI]

Your issue is that the Text(...) initializer takes a LocalizedStringKey rather than a String which supports different types in its string interpolation than plain strings do (which does not include Bool apparently).

There's a couple ways you can work around this.

You could use the Text initializer that takes a String and just displays it verbatim without attempting to do any localization:

var body: some View {
Text(verbatim: "The BOOL 1 value is : Bool 1 = \(defaults.bool(forKey: "MyBool 1"))")
}

Alternatively, you could extend LocalizedStringKey.StringInterpolation to support bools and then your original code should work:

extension LocalizedStringKey.StringInterpolation {
mutating func appendInterpolation(_ value: Bool) {
appendInterpolation(String(value))
}
}


Related Topics



Leave a reply



Submit