Hibernia Hibernia - 1 year ago 56
Swift Question

Value only updating once?

I've got a URL that I've created that looks like :

var PROFILE_URL = "\(URL_BASE)\(Info.sharedInstance.platform!)/\(Info.sharedInstance.region!)/\(Info.sharedInstance.text!)/profile"

the Info.sharedInstances are from a static var I've made :

class Info {

static var sharedInstance = Info()
private init() {}

var region : String!
var platform : String!
var text : String!

I'm then setting those values when I hit certain buttons on my view.

The final button I'm hitting is this :

@IBAction func findUserAction(_ sender: AnyObject) {

if textLabel.text != nil && textLabel.text != "" {
let formattedString = textLabel.text?.replacingOccurrences(of: "#", with: "-")
Info.sharedInstance.text = formattedString


What's happening is the very first time I hit this button the URL gets updated. when I print it out I get a URL and whatever the text.text ends up being, that gets put into the url.

Every time after that the value doesn't get updated. It doesn't matter what else I type the url prints out as it was after the first button press.

Surely every time I'm setting Info.sharedInstance.text = formattedString it should be updating, and right after that I'm calling for the URL to be pressed so I don't understand why this is happening.

Edit: Okay, so if I call

PROFILE_URL = "\(URL_BASE)\(Info.sharedInstance.platform!)/\(Info.sharedInstance.region!)/\(Info.sharedInstance.text!)/profile"

directly after my printout of the URL it works as expected. I guess my question more is why I have to do this. Why if I'm changing the Info.sharedInstance values that make up the URL would the URL not be correct even if I'm not recalling setting the URL? The PROFILE_URL is made up up variables, it seems like when the print(PROFILE_URL) would be called, the PROFILE_URL would grab the most up-to-date version of Info.sharedInstance.

Answer Source

No, you misunderstand.

If you have

var string = "woof"

Then an expression like

var result = "string = \(string)"

Evaluates the quoted string once and repalces the escaped variables with their current values at that moment.

Once that statement is run, result Contains "string = woof". The contents of result Won't change if the value in string changes.