Swift错误:'缺少函数返回'?

时间:2014-07-11 03:07:50

标签: swift

我正在制作一个tic tac toe游戏,我遇到了这个错误,我并不理解:"在预期返回的函数中缺少返回'(位置:字符串,模式:字符串)'&#34 ;. 它正在绘制应该返回" algorResults"的代码块的错误,它应该给出在第一行初始化的位置和模式(两个字符串)。 出了什么问题?请彻底解释一下建议,谢谢! 我的代码:

//Function that implements part of AI that sees where a good place to play is:

func rowcheck(value:Int)->(location:String, pattern:String)? {
    var goodFinds = ["011","101","110"]
    var findFuncs = [checktop, checkbottom, checkmidAcross, checkleft, checkmidDown, checkright, checkLRdiag, checkRLdiag]
    for algor in findFuncs {
        var algorResults = algor(value)
        if find(goodFinds,algorResults.pattern) {
            return algorResults
        }
    }
}

4 个答案:

答案 0 :(得分:9)

如果满足find(goodFinds,algorResults.pattern),您的代码只返回一个值,否则没有返回值。

你可以做的是指定一个默认的返回值并做这样的事情(仅限伪代码):

variable result = defaultvalue

if find(goodFinds,algorResults.pattern) {
        result = algorResults
    }

return result

我应该提一下,我对Swift不熟悉,但这种逻辑可以确保你总是返回一些东西,这样你的方法就能完成契约。

答案 1 :(得分:1)

由于您的返回类型是可选的,您可以这样做:

func rowcheck(value:Int)->(location:String, pattern:String)? {
  var goodFinds = ["011","101","110"]
  var findFuncs = [checktop, checkbottom, checkmidAcross, checkleft, checkmidDown, checkright, checkLRdiag, checkRLdiag]
  for algor in findFuncs {
    var algorResults = algor(value)
    if find(goodFinds,algorResults.pattern) {
        return algorResults
    }
  }
   return nil
}

答案 2 :(得分:0)

您可以使用switch语句。这是我使用的示例:

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let button = DropDownButton()
    switch button {
    case userButton:
        return userButton.dropView.dropDownOptions.count
    case categoryButton:
        return categoryButton.dropView.dropDownOptions.count
    default:
        return 0
    }

快乐的编码可能对某人有帮助

答案 3 :(得分:0)

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let button = DropDownButton()
    switch button {
    case userButton:
        return userButton.dropView.dropDownOptions.count
    case categoryButton:
        return categoryButton.dropView.dropDownOptions.count
    default:
        return 0
    }
相关问题