Swift函数编译器错误'缺少返回' [英] Swift function compiler error 'missing return'

查看:49
本文介绍了Swift函数编译器错误'缺少返回'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试让该函数返回Bool值,但我不明白为什么我会收到错误消息缺少预期返回'Bool'的函数中的返回."并尝试了不同的方法,但我似乎找不到解决方案.任何帮助将不胜感激!

I've been trying to get this function to return a Bool value but I don't understand why i'm getting the error "missing return in a function expected to return 'Bool'. I've been looking around online and tried different things but I can't seem to find a solution. Any help would be appreciated!

func trueSquare(a:[Int], b:[Int]) -> Bool {
    for i in b[0]...b.endIndex {
        if b[i] == a[i]*a[i] {
            return true
        }
        else {
            return false
        }
    }
}

我已经将循环更改为 for 0中的i ...(b.count-1),但是即使使用a和b调用函数,我仍然会遇到相同的错误两者具有相同数量的元素.

I have changed the loop to for i in 0...(b.count - 1) but I am still getting the same error even when I call the function with a and b both having the same numbers of elements.

推荐答案

如果您的数组没有元素怎么办?然后对于每个循环永远不会运行,然后您的方法将不会返回任何结果,这显然是错误的.因此,即使在循环之外,您也需要返回值.

What if your array has no element? Then for each loop never runs and then your method returns nothing which is obviously wrong. So you need to return value even outside of the loop.

但是,你的逻辑不好.您要返回布尔值,具体取决于 b 中的 first 元素是否等于 a * a .

But, your logic is bad. You're returning boolean value depending on if just first element from b is equal to a*a.

因此,逻辑应该类似于:如果每个元素都满足条件,则返回 true ,否则,返回 false .为此,在Swift 4.2+中,您可以使用方法 allSatisfy

So, logic should be something like: if every element meets the condition, then return true, otherwise, return false. To achieve this, in Swift 4.2+ you can use method allSatisfy

func trueSquare(a:[Int], b:[Int]) -> Bool {
    guard a.count == b.count else { return false } // if arrays have different number of elements, return false
    return a.enumerated().allSatisfy {$0.element * $0.element == b[$0.offset]}
}

这篇关于Swift函数编译器错误'缺少返回'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆