Your First Swift 4 & iOS 12 App Online Course – Day 5
Day 5
Printing the value of the random number in the correct label
First creating an IBOutlet for the label to display the target random number and a global targetValue to hold the target random number.
@IBOutlet weak var targetLabel: UILabel!
var targetValue: Int = 0
Connecting this outlet to the label displaying 100 currently.
Since we need to update the targetValue for every round, we create a method startNewRound in which we generate a random value and assign it to targetValue. For swift 4.2+, we can generate random values using “Int.random(in: range)”. I have swift 4.1, therefore I used arc4random_uniform method.
In the updateLabels method, we convert the targetValue to String and assign it to the targetLabel.
Printing the value of the random number in the correct label
Calculating the difference between targetValue and sliderValue and displaying the difference in Alert box
To make sure the difference between currentValue and targetValue stays positive, we multiply the difference by -1.
Then we add the message to display the difference in the Alert box.
var difference: Int
difference = currentValue - targetValue
if difference < 0{
difference = difference * -1
}
let message: String = "The value of the slider is: \(currentValue)" + "\nThe value of the target is: \(targetValue)" + "\nThe value of the difference is: \(difference)"