我试图使用swift代码在apple xcode程序中创建我的第一个游戏,但我遇到了Arrays的问题。这是代码:
//
// 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)
}
}
我在第39行和第39行收到错误40或更具体地说
let firstCardString:String = self.cardNamesArray[randomCardFirst]
let secondCardString:String = self.cardNamesArray[randomCardSecond]
我得到的错误是
视图控制器类型的值没有成员cardNamesArray
因为我对这种语言很陌生,所以我在代码中稍微涉足一下,看看我是否能解决问题,但我所做的一切只会造成另一个错误。任何帮助将非常感激。谢谢!
答案 0 :(得分:1)
为什么在变量之前调用self
(因为你的类没有名为cardNamesArray
的变量),这个变量在你的函数内部(意味着它不是global
),所以不应该致电self
。
替换
let firstCardString:String = self.cardNamesArray[randomCardFirst]
let secondCardString:String = self.cardNamesArray[randomCardSecond]
通过
let firstCardString:String = cardNamesArray[randomCardFirst]
let secondCardString:String = cardNamesArray[randomCardSecond]
如果您只想在函数中使用此cardNamesArray
,可以尝试上面的解决方案。
如果您想在课堂上多次使用它,可以将cardNamesArray
声明为全局变量。