Simple Swift function return error

前端 未结 2 385
花落未央
花落未央 2021-01-29 04:51

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 =          


        
相关标签:
2条回答
  • 2021-01-29 05:45

    You must Implement the return type like this

     func max(inout a: [Int], b: Int)-> Int {
    
     var result = a[0]
     var i: Int
    
     for (i = 1; i <= b; i++) {
      if (a[i] > result) {
          result = a[i]
      }
     }
     return result
    }
    
    0 讨论(0)
  • 2021-01-29 05:47

    The return type is missing in the function declaration:

    func max(inout a: [Int], b: Int) -> 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.

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

        }
        return result
    }
    

    and not

            return result
        }
    }
    
    0 讨论(0)
提交回复
热议问题