0

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
}

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.

Thanks

2
  • 1
    Just a note for clarity, since your first function parameter a (the Array of Int) is not modified in the function call it should not be declared as inout. Commented Oct 29, 2014 at 13:27
  • Thanks JMFR - I am still trying to get to grips with inout. Commented Oct 30, 2014 at 0:21

2 Answers 2

2

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

1 Comment

I am not sure that your first example is valid swift. Can you share where in the documentation it states that you can omit the return arrow ->?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.