How to assign updated value to Text value in Extension SwiftUIenter image description here
extension Text {
public func translate(text: String) -> Text{
var translated = ""
let conditions = ModelDownloadConditions(allowsCellularAccess: true, allowsBackgroundDownloading: true)
GoogleTranslatorManager.shared.translator?.downloadModelIfNeeded(with: conditions) { error in
guard error == nil else { return }
GoogleTranslatorManager.shared.translator?.translate(text) { translatedText, error in
guard error == nil, let translatedText = translatedText else {
// uiView.text = text
return
}
print(translatedText)
translated = translatedText
//**Here: How to assign updated Value to Text ** \\
}
}
return Text(verbatim: translated)
}
}
There are a few issues that I see with your approach.
First, it doesn't make much sense to put this extension on
Text-Textis a view that displays aString. It makes more sense to put the extension onString.Second, if you make an extension on
Stringit would be more typical for the function to operate onself- that is theStringinstance itself, rather than accept an argument.And the final issue is that the translation operations are asynchronous so you can't return a value.
As an extension on
Stringit could look something like:And you would call it something like:
Now, you still have the problem of actually updating the
Textview on the screen. You would use an@Statestring property or an@Publishedproperty in some model and update that string value and the view will update (You may need to dispatch this onto the main queue).However, I don't see the value in creating this as an extension on
String. Is it really a new behaviour that you want all strings to have? It is probably best implemented as a function in your translation manager object.