Need a little bit of help

Hi,

I am making an app that involves having a random color generated from a list of numbers. The user has to click the button with that color. However, there is an issue coming up regarding the generation of random colors. The code is posted below`//
// ViewController.swift
// Button
//
// Created by King Studios on 11/29/19.
// Copyright © 2019 King. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var Score: UILabel!

@IBOutlet weak var Color: UILabel!

var score = 0

var colornum = Int.random(in: 0...3)

var selector = ["red", "yellow", "green", "blue"]



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    var colorlabel = selector[colornum]
    print(colorlabel)
}

@IBAction func RedButton(_ sender: Any) {
    if colorlabel = "Red"{
        
    }
}

@IBAction func YellowButton(_ sender: Any) {
}


@IBAction func GreenButton(_ sender: Any) {
}

@IBAction func BlueButton(_ sender: Any) {
}

@IBAction func LogoSecret(_ sender: Any) {
}

}

`

There is an issue coming up about the variable ‘colorlabel’. Xcode brings up an error in the if statement: if colorlabel = “Red”{ . Xcode is saying that there is the use of an unresolved identifier ‘colorlabel’.

I don’t know what to do. Any help wold be appreciated.

Thanks,

UrAvgCoder

Anson,

Checkout this link about classes!

2 Likes

Define colorLabel outside of viewDidLoad()
Put the code under the var selector…

It can’t find colorLabel in func RedButton because it was created in viewDidLoad() meaning that variable only exists in that function. putting it above that in the same scope as selector and colornum it means that all the functions can access those variables. This is called variable scope.