【问题标题】:Inserting the variables of a function into an array and get the max value将函数的变量插入数组并获取最大值
【发布时间】:2019-11-11 19:35:47
【问题描述】:

我对 swift 字符串和数组有疑问。在一个函数中,我想定义 3 个数字(比如 x、y 和 z),然后用这些变量形成一个数组,并希望返回数组中的 max() 数字。但是,我收到类型错误。 (它要求我换行输入等。 我在下面发布代码。有人可以看看吗:


    func AAA(x: Int, y: Int, z:Int) -> Int {
        let BBB: [Int] = [x, y, z]
        var greatest: Int? = BBB.max()
        return greatest
    }

由于“最大”变量的 Int?类型,但是当我转换 Int 时?到 Int 那么我不能调用数组 BBB 的最大值。

【问题讨论】:

  • 仅供参考,已经有一个函数可以获取最多 3 个(或更多)变量 max(_:_:_:_:)

标签: arrays swift function


【解决方案1】:

返回是一个非可选的 -> Int 并且你返回 greatestInt? ,所以你需要

  func AAA(x: Int, y: Int, z:Int) -> Int {
      return [x, y, z].max()!
  }

【讨论】:

  • 谢谢,你的很干净。我看到我使用了额外的和不必要的数组。在您的解决方案中,我看到如果我制作 max()!在我的,它也在工作。再次感谢您。
猜你喜欢
  • 2016-03-28
  • 2014-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多