【问题标题】:Swift check max value and use快速检查最大值并使用
【发布时间】:2018-08-23 18:50:20
【问题描述】:

我有双数组

var array = [2.50, 2.51, 2.41, 2,1, 1.8, 1.3, 2.9, 3.0]

我需要检查最大值

let maxTuple = array.max()
print(maxTuple)

但它打印我所有的数组 //2.50, 2.51, 2.41, 2,1, 1.8, 1.3, 2.9, 3

如果我得到当前的最大值,我想像这样

var difference = (maxTuple - 2.50)  //0.5
if (difference > 0.1) {
    print("> 0.1")
} else if (difference > 0.2) {
    print("> 0.2")
} else if (difference > 0.3..0.5) {
    print("> 0.3..0.5")   
} else if (difference > 1) {
    print("> 1")
}

我目前如何快速做到这一点?

【问题讨论】:

  • 你的代码打印"Optional(3.0)\n"
  • array.max() 应该可以工作。你可能正在做其他事情。
  • 请注意, maxTuple 是可选的,因此如果不先打开它if let maxTuple = array.max() { 就无法进行任何数学运算。顺便说一句 0.3..0.5 它不是一个有效范围,检查它是否包含你的双精度的正确方法是0.3...0.5 ~= difference
  • @LeoDabus 好的,也许我可以用案例来做这个?没有如果
  • 注意:您需要颠倒您的 ifswitch 案例的顺序,因为它会在您匹配时停止,因此 difference > 0.1 将在任何其他案例之前成功永远不会被检查。

标签: arrays swift sorting


【解决方案1】:

您使用 Array 的 max() 函数是正确的。根据您正在查看的输出可能存在一些混淆,可能是在操场上?例如,您应该看到以下内容,其中最后一行输出是预期的最大值:

由于max() 确实产生了一个可选值(由Optional(3.0) 表示),无论您最终使用该值,您可能希望使用guard of if let 安全地解开它:

guard let maxValue = array.max() else {
    return
}
//Do something with maxValue

【讨论】:

    【解决方案2】:

    请注意,maxTuple 是可选的,因此如果不先打开它,您将无法进行任何数学运算:

    if let maxTuple = array.max() { 
          // your code
    }
    

    顺便说一句 0.3..0.5 它不是一个有效范围,检查它是否包含你的双精度的正确方法是:

    if 0.3...0.5 ~= difference {
        // your code
    }
    

    let array = [2.50, 2.51, 2.41, 2,1, 1.8, 1.3, 2.9, 3.0]
    
    if let maxValue = array.max() {
        print(maxValue)
        let difference = maxValue - 2.5  // 0.5
        switch difference {
        case 0.0...0.1:
            print("greater than 0.0 and less than 0.1")
        case 0.1...0.2:
            print("greater than 0.1 and less than 0.2")
        case 0.2...0.3:
            print("greater than 0.2 and less than 0.3")
        case 0.3...1.0:
            print("greater than 0.3 and less than 1.0") // "greater than 0.3 and less than 1.0\n"
        case 1.0...:
            print("greater than 1.0")
        default:
            print("negative value")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多