如何在Swift中调用函数?

时间:2017-04-02 18:12:36

标签: swift

我不确定为什么我的标签不会更改为问题字符串。

func GenerateQuestion(){
    let FirstNo = Int(arc4random_uniform(10))+1 // first number in sum
    let SecondNo = Int(arc4random_uniform(10))+1 // second number in sum
    let SymbolNo = Int(arc4random_uniform(4))+1 // number which decides the operator in sum
    var OperatorSymbol = ""
    var Question = "" // the question
    var Answer = Int() // holds answer of the sum
    var ButtonNo = Int(arc4random_uniform(4))+1 // number which chooses button to hold correct answer

    switch SymbolNo{
    case 1 : OperatorSymbol = "+";
    Question = "\(FirstNo) + \(SecondNo) = ?";
    self.Lbl.text = Question
    case 2 : OperatorSymbol = "-";
        Question = "\(FirstNo) - \(SecondNo) = ?";
        self.Lbl.text = Question
    case 3 : OperatorSymbol = "/";
        Question = "\(FirstNo) / \(SecondNo) = ?";
        self.Lbl.text = Question
    case 4 : OperatorSymbol = "x";
        Question = "\(FirstNo) x \(SecondNo) = ?;";
        self.Lbl.text = Question
    default : Question = ""
    }

我没有打电话给func generateQuestion,因为我不知道该怎么做。我该怎么办?

1 个答案:

答案 0 :(得分:1)

要调用函数的实例,请键入函数名称,后跟一对带或不带参数的括号。

generateQuestion()

如果您希望在应用加载后立即执行某些操作,则应将其输入到viewDidLoad函数中。

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

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

如上所述,这是一个很好的资源。

同样,如上所述,最好将lowerCamelCase用于函数和变量,并为类和结构保留UpperCamelCase。在Swift指南中可以找到更多内容。

祝你好运!