不等号不符合swift

时间:2016-02-05 12:40:37

标签: swift if-statement operators

当卡片相等时,分数会增加,这是我想要它做的,但是当卡片不相等时它也会增加。我尝试使用不等号,但仍然没有运气。

  @IBAction func SnapButtonTapped(sender: UIButton) {

    if firstRandomNumber == SecondRandomNumber {

        print("index match")

        self.playerScore += 1
        self.playerScoreLabel.text = String(self.playerScore)


    }

    else if firstRandomNumber != SecondRandomNumber {

      print("no match")


    }
    //get the audioPlayer that correspond to the button that they tapped
    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()
}

这是我的其余代码。

import UIKit
import AVFoundation

let firstRandomNumber = Int()
let SecondRandomNumber = Int()
let firstCardString = String()
let SecondCardString = String()

class ViewController: UIViewController {

@IBOutlet weak var FirstCardImageView: UIImageView!
@IBOutlet weak var SecondCardImageView: UIImageView!
@IBOutlet weak var PlayRoundButton: UIButton!
@IBOutlet weak var BackgroundImageView: UIImageView!
@IBOutlet weak var playerScoreLabel: UILabel!

let soundFilenames = ["shuffle", "correct"]
var audioPlayers = [AVAudioPlayer]()



var playerScore: Int = 0

var cardNamesArray: [String] = ["sad", "sleepy","angry"]

var cardNamesArray2: [String] = ["triste", "cansado","enfadado"]


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

    //set up audio player
    for sound in soundFilenames {

        do {
            //try to do something

            let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(sound, ofType:"wav")!)
            let audioPlayer = try AVAudioPlayer(contentsOfURL: url)

            audioPlayers.append(audioPlayer)

        }
        catch {

            //catch the error
            audioPlayers.append(AVAudioPlayer())

        }



    }

    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) {

    self.PlayRoundButton.setTitle("Shuffle Cards", forState: UIControlState.Normal)

    //First Card generate random number
    let firstRandomNumber = Int (arc4random_uniform(3))
    let firstCardString:String = self.cardNamesArray[firstRandomNumber]
    self.FirstCardImageView.image = UIImage(named: firstCardString)

    //Second Card generate random number
    let SecondRandomNumber = Int (arc4random_uniform(3))
    let SecondCardString:String = self.cardNamesArray2[SecondRandomNumber]
    self.SecondCardImageView.image = UIImage(named: SecondCardString)

    //determine matching cards 

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}

1 个答案:

答案 0 :(得分:0)

它的范围。您认为自己正在设置firstRandomNumber& SecondRandomNumber(请不要将变量大写!)用于随机数,但实际上您正在重新声明它们。移除let中的playRoundTapped并将这两者的顶级声明更改为var