NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

SOLVED: string interpolation

Forums > SwiftUI

Hi guys!

A couple of questions whilst im learning swift/swiftui/swiftui 2.0 lol. I know its possible to be able to load a txt file top a string as ive been following the 100 days of swiftUI and loving it. But i have an idea for an app and was wondering if you could have string interpolation inside the txt file so I can have custom questions that fill the string interpolation? I'm trying to find the best way to handle making a madlibs type app to teach myself stuff.

Thanks heaps guys!!


That's not really possible. You can load a string and you can do a find/replace on the contents of the string, but you can't do string interpolation on the loaded string.

And, if you think about it, that's a good thing. What if your loaded string contains \(someVar) but your code doesn't have someVar to interpolate into the string? If you do it in a string literal in your code, then the compiler will flag that someVar doesn't exist but it can't do that if the string is loaded in from a file because it doesn't know what's in the string until it's loaded. So what should happen?



Thanks for replying. That makes sense. so can I use a txt file or a json file and have replace certain unique keywords that are within the string with variables from texfields etc... to make a new edited string to use.

thanks again.


Quick update, I thought I'd let you kn ow what I did to fix it.

I used replacingOccurrences(of:) and used keyword in the story within the JSON file. Now I can control whats in each story by editing the JSON file and not have a new view for each story. Very good. Thanks all :)


Hacking with Swift is sponsored by RevenueCat

SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.

Try it for free

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.