Reputation: 3433
I want to insert a variable character into an UIViewController
label:
e.g. "Currency = $
" when $
is a variable and could be $, £, € depending.
How do you program with this?
Upvotes: 0
Views: 3146
Reputation: 6824
This is a clean approach into this:
func currencySymbol(currency: String) -> String {
switch currency {
case "dollar": return "$"
case "British pound": return "£"
case "yen": return "¥"
///add others as needed
default: return currency
}
}
let string = "Currency = \(currencySymbol("dollar"))" //"Currency = $"
Upvotes: 1
Reputation: 2973
You would do:
var letter = "$"
// You create a new uilabel named label
label.text = "Currency = " + letter
You wanna change your letter var depending on your conditional(s).
Here is an example:
// var currency is a string used to
// read a paragraph
If(currency == "dollar")
letter = "$"
Else if (currency == "British pound")
letter = "£"
Else if (currency == "yen")
letter = "¥"
...
label.text = "Currency = " + letter
Here is a reference: strings and characters: Apple
Hope this helps!
Upvotes: 2
Reputation: 772
I think the best way is to make separate variables for each currency characters and then append them to a string. After you can then set the text of that label to be that string.
let currencyCharacter:String = "$"
let viewControllerLabelText:String = "Currency = " + currencyCharacter
myViewControllerLabel.text = viewControllerLabelText
Upvotes: 2
Reputation: 859
You can use string interpolation by wrapping a variable in \()
like this:
let currency = "$"
currencyLabel.text = "Currency = \(currency)"
This inserts the value of that variable into the surrounding string. Look here for more information on this topic: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html
Upvotes: 1