首页 > 解决方案 > 使用 Dictionary Swift 的 Repeat-While 循环

问题描述

我试图让这个循环正确运行,但它不会继续。如果用户没有输入与字典匹配的值,我需要它向下舍入到最接近的匹配,然后打印该值。

let dict = FitnessScore.powerThrow
var input = 19.30
var correctInput = false

func checkKey(score: Double) -> Bool {
    for (key, _) in dict {
        if key == input {
            correctInput = true
            return true
        }
    }
    return false
}
func getFinnalInput() -> Double {
    repeat {
        input -= 0.1
        checkKey(score: input)
        print("this is the new input value: \(input)")
        print("thie is the new condition: \(checkKey(score: input))")
        return input
        
    } while correctInput == true
}
print("your input score rounded down to \(getFinnalInput())")

struct FitnessScore {
    static let powerThrow = [
        12.50: 100,
        12.40: 99,
        12.20: 98,
        12.10: 97,
        11.90: 96,
        11.80: 95,
        11.60: 94,
        11.50: 93,
        11.30: 92,
        11.20: 91,
        11.00: 90,
        10.90: 89,
        10.70: 88,
        10.60: 87,
        10.40: 86,
        10.30: 85,
        10.10: 84,
        10.00: 83,
        9.80: 82 ]
}

标签: swift

解决方案


let userEntered = "12.9"
var input = Float(userEntered) ?? 0.0

func checkKey(score: Float) -> Bool {
    let dict = FitnessScore.powerThrow
    for (key, _) in dict {
        if key == score {
            return true
        }
    }
    return false
}

func getFinnalInput() -> Float {
    if checkKey(score: input) {
        return input
    } else {
        repeat {
            input -= 0.1
            input = roundf(input * 100) / 100
            print("this is the new input value: \(input)")
            print("thie is the new condition: \(checkKey(score: input))")
            checkKey(score: input)
        } while checkKey(score: input) == false
        return input
    }
}
print("your input score rounded down to \(getFinnalInput())")

推荐阅读