我可以使用 switch 语句来转换 Swift 数组中的每个值吗?

Dic*_*ton 0 arrays switch-statement swift

我想根据每个值在范围内的位置来转换数组的内容。范围标准似乎是最容易在 switch 语句中表示的东西,但我无法将其放在一起或在网上找到类似的示例。

我是初学者,所以请原谅任何明显的愚蠢,但这里有一个我尝试过的示例,应该具有说明性:

    var times = [3,12,4,9,17,22]

    var timeAdjustments: [Int] {
     for i in times {
      switch i {
       case 20...: 50
       case 15...: 70
       case 10...: 80
       case 5...: 90
       case 0...: 100
       default: print("out of range")
    }
    timeAdjustments.append(i)
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,目标是返回如下数组:[100,80,100,90,70,50]。

vad*_*ian 5

我的建议只是(compact)Map数组

let times = [3,12,4,9,17,22]

let timeAdjustments = times.compactMap { item -> Int? in
    switch item {
        case 20...: return 50
        case 15...: return 70
        case 10...: return 80
        case 5...: return 90
        case 0...: return 100
        default : print("\(item) is out of range"); return nil
    }
}
Run Code Online (Sandbox Code Playgroud)