首页 > 解决方案 > 错误:“预期返回 Int 的函数中缺少返回值”

问题描述

下面的第一个函数可以很好地检查 FM 值,但是当我在 else if 语句中为 AM 值添加一些验证时,我收到错误消息: Missing return in a function expected to return Int. 花括号的放置似乎不是问题。

        static var minAMFFrequency: Double = 520.0
        static var maxAMFFrequency: Double = 1610.0
        static var minFMFFrequency: Double = 88.3
        static var maxFMFFrequency: Double = 107.9

    func isBandFM() -> Int {
        if frequency >= RadioStation.minFMFFrequency && frequency <= RadioStation.maxFMFFrequency {
            return 1 //FM
        } else {
            return 0 //AM
        }
    }

修改后的函数有错误:

func isBandFM() -> Int {
        if frequency >= RadioStation.minFMFFrequency && frequency <= RadioStation.maxFMFFrequency {
            return 1 //FM
        } else if frequency >= RadioStation.minAMFFrequency && frequency <= RadioStation.maxAMFFrequency{
            return 0 //AM
        }
    }

标签: iosswiftif-statementreturn

解决方案


您还需要考虑不属于这两种情况的情况。它希望您提供默认返回值。

在第一种情况下,您返回了默认值 0。

第二种情况,如果你frequency既不在第一个范围(由第一个if条件指定)也不在第二个范围(由第二个if条件指定),则需要指定一个默认返回值。

func isBandFM() -> Int {
        if frequency >= RadioStation.minFMFFrequency && frequency <= RadioStation.maxFMFFrequency {
            return 1 //FM
        } else if frequency >= RadioStation.minAMFFrequency && frequency <= RadioStation.maxAMFFrequency{
            return 0 //AM
        }

        return 0   // or whatever value you want to return if frequency is not within FM range or AM range
}

推荐阅读