MrSanfrinsisco MrSanfrinsisco - 6 months ago 9
Swift Question

View Controller can't access elements in arary

I'm trying to create my first game in apples xcode program using swift code but I've come across a problem with Arrays. Here's the code:

//
// ViewController.swift
// War
//
// Created by grayson seymour on 5/13/16.
// Copyright © 2016 SanGames. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var firstCardImageView: UIImageView!
@IBOutlet weak var secondCardImageView: UIImageView!
@IBOutlet weak var playRoundButton: UIButton!
@IBOutlet weak var backgroundImageView: UIImageView!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

self.playRoundButton.setTitle("Play", forState: UIControlState.Normal)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func playRoundTapped(sender: UIButton) {

var cardNamesArray:[String] = ["card0", "card1", "card2", "card3", "card4", "card5", "card6", "card7", "card8", "card9"]

// Creates randomly generated number for first and second card
let randomCardFirst = Int(arc4random_uniform(10))
let randomCardSecond = Int(arc4random_uniform(10))

// checks to see what imageview to set for the cards
let firstCardString:String = self.cardNamesArray[randomCardFirst]
let secondCardString:String = self.cardNamesArray[randomCardSecond]

// sets randomly generated number to imageview for second and first card
self.firstCardImageView.image = UIImage(named: firstCardString)
self.secondCardImageView.image = UIImage(named: secondCardString)
}

}


I'm getting an error on line 39 & 40 or more specifically

let firstCardString:String = self.cardNamesArray[randomCardFirst]
let secondCardString:String = self.cardNamesArray[randomCardSecond]


The error I'm getting is


value of type View Controller has no member cardNamesArray


As I am very new to this language I have dabbled a little bit in the code to see if I could fix the problem but everything I do just creates another error. Any help would be very appreciated. Thanks!

Answer

Why do you call self before your variable (Because your class has no variable called cardNamesArray), this variable is inside your function (mean that it is not global), so shouldn't call self.

Replace

let firstCardString:String = self.cardNamesArray[randomCardFirst]
let secondCardString:String = self.cardNamesArray[randomCardSecond]

By

let firstCardString:String = cardNamesArray[randomCardFirst]
let secondCardString:String = cardNamesArray[randomCardSecond]

If you just want to use this cardNamesArray in your function, you can try this solution above.

If you want to use it multiple time inside your class, you can declare cardNamesArray as a global variable.