Reputation: 15
Swift Beginner
I want to subtract 1 from a label with value "26" every time the "deal" button is pressed. Do I convert it to an Int? And how do I add calculations to it?
I coded cardsAmount.text = "25", which works. But it needs to subtract 1 every time the button is pressed and not assign a hardcoded value.
Also, in the future I would like to add to the number.
Thanks!
class ViewController: UIViewController {
@IBOutlet weak var leftPile: UIImageView!
@IBOutlet weak var rightPile: UIImageView!
@IBOutlet weak var cardsAmount: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func deal(_ sender: Any) {
let shuffled = (2...53).shuffled()
let leftNumber = shuffled[0]
let rightNumber = shuffled[1]
//cardsAmount.text = "25"
leftPile.image = UIImage(named: "c\(leftNumber)")
rightPile.image = UIImage(named: "c\(rightNumber)")
}
.
.
.
}
Upvotes: 1
Views: 633
Reputation: 5225
You can use property observer.
var number: Int = 26 {
didSet {
if number > 0 {
self.cardsAmount.text = "\(number)"
}
}
}
@IBAction func deal(_ sender: Any) {
let shuffled = (2...53).shuffled()
let leftNumber = shuffled[0]
let rightNumber = shuffled[1]
number -= 1 // whenever number value changes, didSet (property observer) will be called
leftPile.image = UIImage(named: "c\(leftNumber)")
rightPile.image = UIImage(named: "c\(rightNumber)")
}
Upvotes: 1
Reputation: 2164
I think you should add a variable
as you are a beginner. Use this:
var initialNumber: Int = 1
var number: Int = 26
@IBAction func deal(_ sender: Any) {
let shuffled = (2...53).shuffled()
let leftNumber = shuffled[0]
let rightNumber = shuffled[1]
number = number - initialNumber
cardsAmount.text = "\(number)" //This is to subtract. Now you can check if it is a negative number and perform operations ahead using if else
leftPile.image = UIImage(named: "c\(leftNumber)")
rightPile.image = UIImage(named: "c\(rightNumber)")
}
You can follow the same approach to add a number. If you want to save the initialNumber
then you can write initialNumber = initialNumber + 1
and then use it. Do let me know if you have any query regarding this answer.
Upvotes: 0