【问题标题】:How to call a function with a parameter如何调用带参数的函数
【发布时间】:2021-01-19 10:31:49
【问题描述】:

enter image description here

func loveCaclculator(number: Int)-> Int {

    Int.random(in: 0..<1000)
    return number
}

loveCaclculator(number)
print(loveCaclculator(number: 4))

我在调试器中收到错误“在范围内找不到数字”,我不知道如何解决它

【问题讨论】:

    标签: swift function swift-playground


    【解决方案1】:

    发生错误是因为参数number在函数外不可见。

    您的代码无论如何都不使用参数,例如,您必须将函数的结果分配给变量

    func loveCalculator() -> Int {
        let number = Int.random(in: 0..<1000)
        return number
    }
    
    let result = loveCalculator()
    print(result)
    

    另一方面,如果您想将最大数量作为参数传递,则必须编写

    func loveCalculator(maxValue : Int) -> Int {
        let number = Int.random(in: 0..<maxValue)
        return number
    }
    
    let result = loveCalculator(maxValue: 20)
    print(result)
    

    【讨论】:

      【解决方案2】:

      消息很明确:number 此时未定义,您不会像在 print 语句中那样忘记传递 4 吗?

      loveCaclculator(number: 4)
      print(loveCaclculator(number: 4))
      

      【讨论】:

        猜你喜欢
        • 2016-11-13
        • 1970-01-01
        • 2019-11-29
        • 2017-12-25
        • 1970-01-01
        • 2014-04-02
        • 1970-01-01
        • 1970-01-01
        • 2013-08-19
        相关资源
        最近更新 更多