Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Functions in Swift Adding Power to Functions Function Parameters

Ingunn Augdal Fløvig
Ingunn Augdal Fløvig
1,507 Points

Error: "Unexpected non-void return value in void function" trying to make a function to return the remainder value

The task is "In this task we're going to write a simple function that takes two numbers and returns the remainder of dividing one number by the other.

Step 1: Declare a function named getRemainder that takes two parameters, aand b, both of type Int, and returns the value, also of type Int, obtained by carrying out the operation a modulo b. In case you've forgotten, the modulo operator is also called the remainder operator.

Step 2: The local names of the parameters are convenient but they make it hard to figure out the meaning of the function when we call it. Add two external names - value, for the first parameter and divisor for the second."

I tried making a constant named remainder and storing a%b in that, and then return that value, but I'm not sure why this doesn't work.

functions.swift
// Enter your code below

func getRemainder(value a: Int, divisor b: Int) {
 let remainder: Int = (a % b)
 return remainder
  }

2 Answers

Rogier Nitschelm
seal-mask
.a{fill-rule:evenodd;}techdegree
Rogier Nitschelm
iOS Development Techdegree Student 5,461 Points

What the compiler is saying, is that you are returning a value (the remainder), but the function signature does not specify a return value. When you return a value from a function, you will have to write it out. Like so:

func getRemainder(...) -> Int {
    ...
    return someNumber
}
Ingunn Augdal Fløvig
Ingunn Augdal Fløvig
1,507 Points

That worked, thanks! Do I always have to specify the type of the return value when creating a function? Can't Swift infer it?

Rogier Nitschelm
seal-mask
.a{fill-rule:evenodd;}techdegree
Rogier Nitschelm
iOS Development Techdegree Student 5,461 Points

Swift will only infer the return type when there is no return value. So you could write the absence of a return value in two ways:

func someFuncA() {
...
}

// or

func someFuncB() -> Void {
   ...
}

Other than that Swift won't infer the return type. I think they choose to be explicit about it.