Swift Error: Cannot convert return expression of type ‘()’ to return type ‘Int.’
Image via Author

Swift Error: Cannot convert return expression of type ‘()’ to return type ‘Int.’


One of the things about learning to code is knowing the intricacies of how the various elements work. This will save you countless hours in debugging, therefore increasing your productivity.

In this article, I’m going to use an error message to give you a better understanding of operators, operands and the return keyword.

Let’s do this


The Error:



var count = 0

func addCount() -> Int {
    
    return count += 1
    
}

let myCount = addCount()

print(myCount)

//
//error: deBug.playground:8:18: error: cannot convert return expression of type '()' to return type 'Int'
//    return count += 1
//           ~~~~~~^~~~
        

The variable count is initialised with the value 0.

addCount() takes no parameters and returns an Int.

In the body of the function, the return keyword is followed by the addition assignment operator += that performs an addition on the two operands.

The value returned from addCount() is assigned to the constant named myCount and then printed.

However, the code doesn’t quite do what it’s expected.


//
//error: deBug.playground:8:18: error: cannot convert return expression of type '()' to return type 'Int'
//    return count += 1
//           ~~~~~~^~~~        

Instead of getting the integer 1, we see an error pointing to the addition assignment operator.

The error message says it “cannot convert return expression of type ‘()’ to return type ‘Int.”

This means the function is expected to return an Int but instead, it’s returning nothing ().

This is happening because when the addition assignment operator is used to perform on two operands, count and integer 1, the result of the operation is assigned to the left operand — in this case count.

return doesn’t receive the result of the operation and therefore returns (), meaning Void.


The BugFix:


var count = 0

func addCount() -> Int {
    
    count += 1
    
    return count
    
}

let myCount = addCount()

print(myCount)


// 1
        

Seeing that count is holding the result of the addition assignment operation, to fix the error, we need to pass the value held in count to return.


Debugging Tip:

When your code doesn’t behave as expected, start with the clue given by the error message, then break the various elements apart and check what is being returned and why.

By asking yourself what is being returned and why it’s being returned, you’ll get to properly understand how programming and the language you're using work.

Never assume, always question.

要查看或添加评论,请登录

Ijeoma Nelson的更多文章

社区洞察

其他会员也浏览了