尝试在我的代码中调用函数,但无法正常工作

时间:2019-09-10 20:19:10

标签: swift

所以我创建了一个名为startover1()的函数,我试图在另一个函数中调用它,但是Xcode一直在说错误。

我尝试将函数放在不同的位置,但是好像没有读取该函数。

import Foundation
import UIKit

class BU: UIViewController {

    let allBUSentences = BUSentenceBank()
    var sentenceNumber2 : Int = 0


    @IBOutlet weak var BUSentenceLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        let BUfirstQuestion = allBUSentences.list2[sentenceNumber2]
        BUSentenceLabel.text = BUfirstQuestion.BUSentenceText
    }


    @IBOutlet var BUNextButton: UIButton!

    @IBAction func BUNext2(_ sender: Any) {

        sentenceNumber2 = sentenceNumber2 + 1
        nextSentence()


    }

    func nextSentence() {

        if sentenceNumber2 <= 19 {

            BUSentenceLabel.text = allBUSentences.list2[sentenceNumber2].BUSentenceText
        }
        else{

            let alert2 = UIAlertController(title: "Game Over", message: "Restart and keep drinking?", preferredStyle: .alert)

            let restartAction2 = UIAlertAction(title: "Restart", style: .default) { (UIAlertAction) in self.startover1()

            }
            alert2.addAction(restartAction2)

            present(alert2, animated: true, completion: nil)

        }            

        func startover1() {

            sentenceNumber2 = 0
            nextSentence()
        }           
    }

}

希望它将能够识别该方法。错误是“ BU”类型的值没有成员“ startover1”

1 个答案:

答案 0 :(得分:1)

问题在于nextSentence嵌套在另一个func声明中。要使其工作,只需将声明移至{brackets}定义的先前函数范围之外即可。检出:

import Foundation
import UIKit

class BU: UIViewController {

let allBUSentences = BUSentenceBank()
var sentenceNumber2 : Int = 0


@IBOutlet weak var BUSentenceLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    let BUfirstQuestion = allBUSentences.list2[sentenceNumber2]
    BUSentenceLabel.text = BUfirstQuestion.BUSentenceText
}


@IBOutlet var BUNextButton: UIButton!

@IBAction func BUNext2(_ sender: Any) {

    sentenceNumber2 = sentenceNumber2 + 1
    nextSentence()


}

func nextSentence() {

    if sentenceNumber2 <= 19 {

        BUSentenceLabel.text = allBUSentences.list2[sentenceNumber2].BUSentenceText
    }
    else{

        let alert2 = UIAlertController(title: "Game Over", message: "Restart and keep drinking?", preferredStyle: .alert)

        let restartAction2 = UIAlertAction(title: "Restart", style: .default) { (UIAlertAction) in self.startover1()

        }
        alert2.addAction(restartAction2)

        present(alert2, animated: true, completion: nil)

    }            
    startover1() //This is not a declaration, but a call
}

//This is startover1 declaration
func startover1() {

    sentenceNumber2 = 0
    nextSentence()
}  

}