nested if statement in swift function - swift

The following function counts down a red to green light, then counts the reaction time for the user to hit a button after the green light is displayed.
func updateCounter() {
timerInt -= 1
if timerInt == 2{
light.image = UIImage(named: "r.png")
} else if timerInt == 1 {
light.image = UIImage(named: "yellow.png")
} else if timerInt == 0 {
light.image = UIImage(named: arc4random_uniform(2) == 0 ? "no.png" : "g.png")
timer.invalidate()
startStop.isEnabled = true
scoreTimer = Timer.scheduledTimer(timeInterval: 0.0001, target: self, selector: #selector(ViewController.updateScoreTime), userInfo: nil, repeats: true)
}
}
Where it states else if timerInt == 0, the user is given a random function. An image will either turn green or an "x" is displayed.
If the x is displayed, I would like the user to to have to hit a button that states game over to restart the red light sequence.
If a green light is displayed, I would like the user to have to test their reaction time.
This is how the function already runs now, except it does not change if the x is displayed. I guess I would like the function to run as follows:
if timeInt == 0 and green light is chosen
then run test reaction time
else if timeInt == 0 and x is chosen
then end reaction time and run game over button
How can I achieve this?

I am not exactly sure what you are trying to achieve, so I did my best. Try this:
func updateCounter() {
timerInt -= 1
if timerInt == 2{
light.image = UIImage(named: "r.png")
} else if timerInt == 1 {
light.image = UIImage(named: "yellow.png")
} else if timerInt == 0 {
let green = (arc4random_uniform(2) == 0)
light.image = UIImage(named: (green ? "g.png" : "no.png"))
if green {
// run test reaction time
} else {
//end reaction time and run game over button
}
// NOTE: Do you mean `scoreTimer.invalidate()`?
timer.invalidate()
startStop.isEnabled = true
// NOTE: This time interval seems WAY too small ↓↓↓↓↓↓: it is only a millisecond!
scoreTimer = Timer.scheduledTimer(timeInterval: 0.0001, target: self, selector: #selector(ViewController.updateScoreTime), userInfo: nil, repeats: true)
}
}
Replace the first two comments (aka lines beginning with //) with the appropriate code, and take note of the third and fourth comments.

Related

How can i make a functionality that uses if statements to switch images based on a random result

I have this simple app that is a dice app that has two dice. I want to show a label "JACKPOT!" at alpha(transparency) 1.0 when the user has both dices land with the same number.
Example:
User rolls DiceOne && DiceOne label "jackpot!" changes alpha to 1.0
I tried using an if statement with an array of 5 images of each possible dice number ie: 1,2,3,4,5,6
The code that i wrote worked one day then the next day it no longer works.
let dicearray = [#imageLiteral(resourceName: "DiceOne"), #imageLiteral(resourceName: "DiceTwo"), #imageLiteral(resourceName: "DiceThree"), #imageLiteral(resourceName: "DiceFour"), #imageLiteral(resourceName: "DiceFive"), #imageLiteral(resourceName: "DiceSix")]`
func jackpotShows() {
if diceImageView1.image == dicearray[0] && diceImageView2.image == dicearray[0] {
jackpotLabel.alpha = 1.0
}
}
Change your if statement from
//This is wrong
if diceImageView1.image == dicearray[0] && diceImageView2.image == dicearray[0] {
jackpotLabel.alpha = 1.0
}
to
//This is right
if diceImageView1.image == diceImageView2.image {
jackpotLabel.alpha = 1.0
}
Or, alternatively, you could do a for loop:
//This is right
for image in diceArray {
if diceImageView1.image == image && diceImageView2.image == image {
jackpotLabel.alpha = 1.0
}
}

How hide UILabel after 2 seconds Swift?

When I taped button UILabel appears and immediately disappears again. I need it to disappear after a few seconds. It's my first app and I can't solve this problem.
Thanks!
func done() {
if sauserImageView.isHidden == false && cupImageView.isHidden == false && spoonImageView.isHidden == false {
winningLabel.isHidden = false
}
}
You can perform a delayed action by using the DispatchQueue API, e.g.
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.label.isHidden = true
}
Or if you want to animate the hiding, use UIView.animate(withDuration:animations:) or UIView.animate(withDuration:delay:options:animations:completion:) e.g.:
UIView.animate(withDuration: 2) {
self.label.alpha = 0
}
Good luck!

How to display milliseconds in a countdown timer label?

I'm creating a game where you have to tap as much circles as possible for 10 seconds. If the user taps a circle, counter+=0.15 milliseconds, but if he misses it, counter-=0.15
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameScene.updateTimer), userInfo: nil, repeats: true)
Now this is the timer function:
func updateTimer() {
counter-=1
timerLabel.text = "\(counter)"
if counter == 0 {
timerLabel.fontColor = UIColor.red
timerLabel.text = "TIME'S UP"
resetGameLabel.isHidden = false
Circle.removeFromParent()
timer.invalidate()
}
if counter < 0 {
timerLabel.fontColor = UIColor.red
timerLabel.text = "TIME'S UP"
resetGameLabel.isHidden = false
Circle.removeFromParent()
timer.invalidate()
}
}
Now what I want is to display milliseconds on that timerLabel.text, how can I do it?
Hope this helps:
func currentTimeInMilliSeconds()->Int64 {
return Int64(Date().timeIntervalSince1970 * 1000)
}
var counterInMilliSeconds = currentTimeInMilliSeconds()
If You Create a var timeToDisplay: Double and make it equals to the time, you can add or remove the milliseconds you want, and then just make the label Equals to var timeToDisplay instead of your counter.

Can't increment variable in Swift - not throwing any errors

(I'm very new to programming, so layman-friendly answers are certainly appreciated)
I'm working on a game played with two teams. I have a button that does a check for which team is up and then updates that team's score. The code runs with no errors but the score doesn't update when the button is pressed.
In my model file I declare
var teamOneScore = 0
var teamTwoScore = 0
var teamCounter = 2
In the view controller I have
#IBAction func buttonPressed(sender: AnyObject) {
if timer.valid && teamCounter % 2 == 0 {
++teamOneScore
} else if timer.valid && teamCounter % 2 != 0 {
++teamTwoScore
}
}
In viewDidLoad
if teamCounter % 2 == 0 {
scoreLabel.text = "Score: \(teamOneScore)"
} else {
scoreLabel.text = "Score: \(teamTwoScore)"
}
When the view loads, scoreLabel correctly displays 0, but when I press the button, the displayed score doesn't go up. The timer and teamCounter checks are working fine everywhere else in the code and I have another button that increments teamCounter (which is also stored as an int in the model) with no problems. So all the separate components of buttonPressed seem to be working fine and I don't have any errors to go on. I'm stumped.
You have to move the text setting in an extra method. Right now the text only gets set in viewDidLoad - that function will not be triggered more than once however.
change your viewDidLoad to something like
updateUI()
add a new function
func updateUI() {
if teamCounter % 2 == 0 {
scoreLabel.text = "Score: \(teamOneScore)"
} else {
scoreLabel.text = "Score: \(teamTwoScore)"
}
}
and call that method as the last thing in the button action:
#IBAction func buttonPressed(sender: AnyObject) {
if timer.valid && teamCounter % 2 == 0 {
++teamOneScore
} else if timer.valid && teamCounter % 2 != 0 {
++teamTwoScore
}
updateUI()
}
When you create the scoreLabel in viewDidLoad, you assign it a text value of "Score: \(teamOneScore)" which is great. However, when you increment the teamOneScore variable, the actual UILabel does not know to change its text. It assumes you wanted to display Score: 0. Even if a variable changed its value, that label has already been created and will continue to display whatever text was initialized.
What you need to do in your buttonPressed function is add
scoreLabel.text = "Score: \(teamOneScore)" or
scoreLabel.text = "Score: \(teamOneScore)" if it was team 2 that scored.
after you increment the score. This is what allows the label's text to actually change.

Debugging code: carousel display string arrays

I'm coding a carousel that display a string array. The string element that is selected is to be displayed in a UIView.
var plotValue:Int = 0
var flag:Int = 1
let plotList: [String] = ["Phenotype","SNP","Synthesis","PheWAS","Circos"]
Basically, the user can swipe left or right the UILabel gets updated with a new value from the plotList.
Swipe left decrements a counter by -1, swipe right increments a counter by +1.
If the user reaches the initial value of the plotList[0] continues swiping left, the code will wrap around and start from the maximum element in the plotList.
If the user reaches the maximum value of the plotList and continues to swipe right, the code will wrap around and start from the plotList[0].
Once the users taps the UIView, another process is launched.
var swipeCarouselLeft: UISwipeGestureRecognizer =
UISwipeGestureRecognizer(target: self, action: "carouselLeft")
swipeCarouselLeft.direction = UISwipeGestureRecognizerDirection.Left
self.labelView.addGestureRecognizer(swipeCarouselLeft)
var swipeCarouselRight: UISwipeGestureRecognizer =
UISwipeGestureRecognizer(target: self, action: "carouselRight")
swipeCarouselRight.direction = UISwipeGestureRecognizerDirection.Right
self.labelView.addGestureRecognizer(swipeCarouselRight)
var tapButton:UITapGestureRecognizer =
UITapGestureRecognizer(target: self, action: "carouselTap")
self.labelView.addGestureRecognizer(tapButton)
Here are the functions defined.
func carouselLeft(){
AudioServicesPlaySystemSound(1052)
flag = -1
getLabel(flag)
}
func carouselRight(){
AudioServicesPlaySystemSound(1054)
flag = 1
getLabel(flag)
}
and
func getLabel(flag: Int){
plotValue = plotValue + flag
println("plotValue \(plotValue)")
switch plotValue {
case (plotList.count):
plotValue = 0
case (-1):
plotValue = plotList.count - 1
default:
plotValue = 0
}
UIView.animateWithDuration(2, animations: { () -> Void in
self.labelOutlet.textColor = UIColor.blueColor()
})
self.labelOutlet.text = plotList[plotValue]
println("\(plotList[plotValue])UIView")
}
func carouselTap(){
AudioServicesPlaySystemSound(1057)
}
Basically, when user swipe the resulting string is either the first or last element in the plotList array, none of the other elements in the array are shown.
Maybe I'm overthinking this and there's a simpler way to do this? or the Apple "preferred" way of doing this? or a more OOP??
Changed the logic to this and works and will wrap in both directions.
func getLabel(flag: Int){
if (flag == -1 && plotValue == 0){
plotValue = plotList.count - 1
}
else if (flag == 1 && plotValue == plotList.count - 1)
{
plotValue = 0
}
else
{
plotValue = plotValue + flag
}
UIView.animateWithDuration(2, animations: { () -> Void in
self.labelOutlet.textColor = UIColor.blueColor()
})
self.labelOutlet.text = plotList[plotValue]
}