Is there a way in Swift to assign variables by referencing the String parameter passed to the function?
My goal is to write a generic function that allows me to update UILabel text based on its String parameter. In particular, the function must find the UILabel by matching its variable name with the String parameter that it received.
When I try to join two strings when assigning a value to a variable, I get the following errors: "String" does not convert to "Int", and "String" does not convert to "UILabel".
Maybe I'll do it all wrong.
import UIKit
class ViewController: UIViewController {
var appleCounter = 0, appleFarms = 1
var orangeCounter = 0, orangeFarms = 1
var grapeCounter = 0, grapeFarms = 1
@IBOutlet weak var appleLabel: UILabel!
@IBOutlet weak var orangeLabel: UILabel!
@IBOutlet weak var grapeLabel: UILabel!
func updateFruitLabel(fruitString: String) {
let fruitCount: Int = (fruitString + "Counter")
let fruitFarms: Int = (fruitString + "Farms")
let fruitLabel: UILabel = (fruitString + "Label")
fruitLabel.text = "\(fruitString)s: \(fruitCount), \(fruitString) farms: \(fruitFarms)"
}
@IBAction func appleTapped(sender: UIButton) {
appleCounter++
updateFruitLabel("apple")
}
@IBAction func orangeTapped(sender: UIButton) {
orangeCounter++
updateFruitLabel("orange")
}
@IBAction func grapeTapped(sender: UIButton) {
grapeCounter++
updateFruitLabel("grape")
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}