TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Help combining String Interpolation with replacingOccurrences

Forums > SwiftUI

Hello everyone

My question is: How can I combine String Interpolation with the replacingOccurrences function. Here is an example use

Text("Hello \(Text("world").italic())")
// Outputs: 
// Hello world (italicized)

let testString = "Test1\nTest2 — Test3 {B}{5}"

if testString.contains("{B}") {
    Text(testString.replacingOccurrences(of: "{B}", with: "\(Text("{B}").italic())"))
}

// Outputs: 
// Test1
// Test2 — Test3 Text(storage:SwiftUI.Text.Storage.anyTextStorage(<Localized-TextStorage: 0x0000600002114af0>: "{B}"), modifiers: [SwiftUI.Text.Modifier.italic]){5}

I'm creating a fun test app to recreate the Magic the Gathering x Warhammer 40k card set visually in SwiftUI. I've pretty much got the cards done, but I'm being utterly defeated by the body section as it requires some nifty coding.

Goal

My goal is to use String Interpolation to identify when strings such as "{B}" and "{5}" etc appear in the string, and then replace them with (Text(Image("imageName"))) to display the associated symbol that I have saved in the assets folder.

Test

To test this out, I am simply trying to replace "{B}" with "(Text("{B}").italic())"), however the output is unexpected. Instead of seeing {B}, I see Text(storage:SwiftUI.Text.Storage.anyTextStorage(<Localized-TextStorage: 0x0000600002114af0>: "{B}"), modifiers: [SwiftUI.Text.Modifier.italic])

Hypothesis

My hypothesis is once I undertsand and solve for this, I can then apply this thinking to display something like the following card with it's symbols and italics.

Here is a GitHub link to the page where I am writing this code in the project files.

Thank you for your time and guidance.

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.