简单的Swift函数返回错误 [英] Simple Swift function return error

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

问题描述

我正在将一些算法伪代码转换为Swift,并具有以下功能:

I am converting some algorithm pseudo code to Swift and have the following function:

func max(a: [Int], b: Int) {

  var result = a[0]

  var i: Int

  for (i = 1; i <= b; i++) {
      if (a[i] > result) {
          result = a[i]
      }
  }
  return result
}

返回结果时出现错误:'Int'不能转换为'()'

I get an error when returning the result: 'Int' is not convertible to '()'

我在网上搜索过,找不到这个问题的答案,希望有人能指出我正确的方向.

I've had a search online and can't find an answer to this question and am hoping someone can point me in the right direction.

谢谢

推荐答案

函数声明中缺少返回类型:

The return type is missing in the function declaration:

func max(inout a: [Int], b: Int) -> Int {
                                 ^^^^^^

没有返回类型,swift默认为空的元组(),这就是错误的含义:int不能转换为空的元组.

Without a return type, swift defaults to an empty tuple (), and that's what the error means: int is not convertible to an empty tuple.

还请注意,您的return语句放错了位置:它应该在最后一个右括号之前

Also note that your return statement is misplaced: it should go right before the last closing bracket

    }
    return result
}

不是

        return result
    }
}

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

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