LakaLe_
LakaLe_

Reputation: 454

How to dynamically process text in Swift

I need a sugestion about dynamically processing and storing text depending on variables.

I've got a core text which is a content of my Swift-iOS application. But some part of this text change depend on user data, e.g.

"{{ if user.age > 15}} You are very young {{ else }} You are not too young {{ end }} but I will show you some magic in this app."
  1. I have no idea how and where store such text in my app (store whole text in file, or split it and store separately),
  2. How to process such text to display it depending on user variables.

Thank you for you sugestion.

Upvotes: 0

Views: 244

Answers (2)

DeFrenZ
DeFrenZ

Reputation: 2252

The proper way to do this is to define a key for the texts (e.g.: WelcomeTextUserYoung and WelcomeTextUserOld), then associate those keys with the entire strings in the .string file. You'll have to write the logic (user.age > 15) in the class that shows the string (or in a common class if it's shown in more than one place).

I know that writing the whole string two times might sound as redundant and code repetition, but you never know if translating the text it remains separated as it is in english. So better implement good practices from the start, even if you don't think of localising the app ;)

Upvotes: 1

pomo_mondreganto
pomo_mondreganto

Reputation: 2074

You can use NSUserDefaults to store user data. Example:

var storage = NSUserDefaults.standartUserDefaults()
storage.setInteger(yourInt, forKey: "just a string using which you can access the value")
storage.setObject(yourObject, forKey: "the same as above") //yourObject can be a string, or a NSData
storage.synchronize()

To update UI elements you can use the timer connected to function, in which you get the object from NSUserDefaults and change the needed element (label, button, etc.)

Upvotes: 0

Related Questions