Как проверить массив для содержимого, основанного на другой переменной, использовать окно предупреждения через оператор if? - PullRequest
0 голосов
/ 25 апреля 2018

В настоящее время я работаю над небольшим приложением Bingo.У меня есть несколько проблем с этим, однако.

Во-первых, у меня есть кнопка, при нажатии которой меняются изображения, показывающие, что эта часть помечена (предназначена для обозначения набранных номеров).У меня есть утверждение if следующим образом:

 if BOneButton.isSelected && IOneButton.isSelected && NOneButton.isSelected && GOneButton.isSelected && OOneButton.isSelected {

        winConditionLabel.text = "You win!"

        func createAlert(_ sender: UIButton) {

            let alert = UIAlertController(title: "Bingo!", message: "You win!", preferredStyle: .alert)

            let action1 = UIAlertAction(title: "Play Again?", style: .default) { (action) in

                self.NewBoardAction(sender)
                self.dismiss(animated: true, completion: nil)
            }

            alert.addAction(action1)
            present(alert, animated: true, completion: nil)

        }

    }

У меня есть несколько проблем с этим.Во-первых, окно оповещения не появится.Я сделал что-то неправильно?(Я впервые пытаюсь использовать Alerts, так что это очень вероятно.) Во-вторых, метка, которую я использовал для проверки того, что программа в первую очередь проходит через оператор if, обновляется только после отмены выбораПоследняя кнопка в ряду.Это основная проблема, которую я пытаюсь исправить прямо сейчас.И, наконец, у меня возникают проблемы с проверкой массива callNumbers (который состоит именно из этого - всех вызываемых номеров), чтобы убедиться, что выбранные номера были вызваны.

У меня изначально былокак-то так:

if BOneButton.isSelected && IOneButton.isSelected && NOneButton.isSelected && GOneButton.isSelected && OOneButton.isSelected && calledNumbers.contains(Int(randomBOne.text)) && calledNumbers.contains(Int(randomIOne.text)) && calledNumbers.contains(Int(randomNOne.text)) && calledNumbers.contains(Int(randomGOne.text)) && calledNumbers.contains(Int(randomOOne.text)) {

// do stuff here

}

Но это не сработает вообще.Есть лучший способ сделать это?Я бы очень признателен за любую помощь!

Относительно проблемы с проверкой массива.Вот код для первой буквы.Другие по сути делают то же самое:

@IBAction func newNumberAction(_ sender: Any) {


    // B NUMBERS

    let randomLetter = ["B", "I","N","G","O"]
    let randomIndex = Int(arc4random_uniform(UInt32(randomLetter.count)))  // Gives random number from 0 - 4

    if (randomLetter[randomIndex]) == (randomLetter[0]) // if statement for each index/letter possibility {

        let randomBIndex = Int(arc4random_uniform(UInt32(listBNumbers.count))) // listBNumbers is the original array that randomizes a number from 1 - 15

        if randomBIndex < 1 // makes sure there are still B numbers remaining and if not runs the newNumberAction again {

            newNumberAction((Any).self)

        } else {
        let newBNumber = "\(listBNumbers[randomBIndex])" // creates unique variable for random BNumbers
        let combinedNumber = (randomLetter[0]) + newBNumber
        var calledBNumbers = [Int]() // creates array for called BNumbers
        calledBNumbers.append(Int(newBNumber)!) // adds called B Number into new array
        listBNumbers.remove(at: (Int(randomBIndex))) // removes B Number from bank of possible numbers that could be called, this should ensure that no number can be called twice

        calledNumbers += calledBNumbers // adds called B Numbers to new array that will be used later to verify BINGO

         newNumLabel.text = combinedNumber
        // this randomizes the number and combines it with 'B' then displays it in the label's text. This is used to display the next called Number.
        }

Я знаю, что приложение работает, проверяя метку, которая дает мне количество переменных в массиве namedNumbers.Опять же, я прошу прощения, что изначально не предоставил достаточно информации.

1 Ответ

0 голосов
/ 25 апреля 2018
  1. Ваша первая проблема - предупреждение не появится, потому что у вас есть функция, объявленная внутри оператора if.Создайте его вне оператора if, а затем вызовите его внутри оператора if

  2. Ваша вторая проблема не включает достаточно контекста в коде, чтобы кто-либо мог вам помочь.Откуда кто-нибудь, кроме вас, узнает, что такое «последняя кнопка в строке» ?

  3. Ваша последняя проблема имеет ту же проблему, что и вторая проблема, "У меня проблемы с проверкой массива callNumbers" .В вашем вопросе нет массива, так как кто-нибудь может помочь вам с выявлением проблемы?

Это должно решить вашу первую проблему:

if BOneButton.isSelected && IOneButton.isSelected && NOneButton.isSelected && GOneButton.isSelected && OOneButton.isSelected {

        winConditionLabel.text = "You win!"

        createAlert() // now that this inside of the if statment it will run
 }

// this should be declared outside of the if statement
func createAlert() {

        let alert = UIAlertController(title: "Bingo!", message: "You win!", preferredStyle: .alert)

        // your alert's code

 }

Вы добавилиинформация о массиве, но там все еще недостаточно контекста.Это лучшее, что я мог сделать, основываясь на том, что, я полагаю, вы хотели.Ваш код все еще не достаточно понятен.Вы должны были добавить все массивы с информацией foo.Сейчас я добавил массив var listBNumbers = ["X", "Y", "Z"] с X,Y,Z в качестве значений listBNumbers для использования в вашем коде, поскольку вы ничего не предоставили.

var listBNumbers = ["X", "Y", "Z"]

let randomLetter = ["B", "I","N","G","O"]

/*
// YOUR ORIGINAL CODE
let randomIndex = Int(arc4random_uniform(UInt32(randomLetter.count))) 
*/

// 1. TEMPORARILY set this to 0 so that if statement below will run. Delete this and uncomment out your original code above when finished
let randomIndex = 0 

if randomLetter[randomIndex] == randomLetter[0] {

        /*
        // YOUR ORIGINAL CODE
        // randomIndex is of type INT there is no need to cast it as Int again in step 7B when your removing it from the listBNumbers array
        let randomBIndex = Int(arc4random_uniform(UInt32(listBNumbers.count)))
        */

        // 2. TEMPORARILY set this to 2 so that the else statement below will run. Delete this and uncomment out your original code above when finished 
        let randomBIndex = 2

        if randomBIndex < 1 {

            // I have no idea what this is
            newNumberAction((Any).self)

        } else {

            // 3. newBNumber is now: Z
            let newBNumber = "\(listBNumbers[randomBIndex])"
            print("newBNumber: \(newBNumber)")

            // 4. combinedNumber is now: BZ
            let combinedNumber = randomLetter[0] + newBNumber
            print("combinedNumber: \(combinedNumber)")

            // 5. THIS IS AN ARRAY of type INT it will not accept Strings
            var calledBNumbers = [Int]()

            // 6A. newBNumber is of type STRING not a type INT. This line below CRASHES because what your saying is calledBNumbers.append(Int(Z)!). How can you cast a Z to an Int?
            calledBNumbers.append(Int(newBNumber)!) // newBNumber contains the letter Z

            // 6B. THIS IS MY ASSUMPTION seems like you wan to use
            calledBNumbers.append(randomBIndex)
            print("calledBNumbers: \(calledBNumbers.description)")

            // 7A. check to see if the index your looking for is inside the listBNumbers array
            if listBNumbers.indices.contains(randomBIndex){

                // 7B. randomBIndex is ALREADY of type Int. Why are you casting it >>>Int(randomBIndex)
                listBNumbers.remove(at: randomBIndex)

                print("listBNumbers: \(listBNumbers.description)")
            }

            // 8. There is no context for me to even try and figure out what calledNumbers is so I can't give you any info about it
            calledNumbers += calledBNumbers

            // combinedNumber contains: BZ from the step 4 so that is what your newNumLabel.text will show
            newNumLabel.text = combinedNumber
            }
        }

Вот способ очистки этого кода, так чтоэто более читабельно.Вам нужно разбить все это на более мелкие функции, чтобы они были более читабельными:

if areButtonsSelected() == true && doesCalledNumbersContainBingo() == true{
    // do stuff here
}

func areButtonsSelected() -> Bool {

    if BOneButton.isSelected && IOneButton.isSelected && NOneButton.isSelected && GOneButton.isSelected && OOneButton.isSelected{
        return true
    }

    return false
}

func doesCalledNumbersContainBingo() -> Bool {

    let b = Int(randomBOne.text)
    let i = Int(randomIOne.text)
    let n = Int(randomNOne.text)
    let g = Int(randomGOne.text)
    let o = Int(randomOOne.text)

    if calledNumbers.contains(b) && calledNumbers.contains(i) && calledNumbers.contains(n) && calledNumbers.contains(g) && calledNumbers.contains(o){
        return true
    }

    return false
}
...