GeorGios GeorGios - 5 months ago 23
Swift Question

Swift: Cannot convert return expression of type '(Int, Int)' to return type 'Int"

I recently wrote this code in Swift below. I used structures to get a point(which is the origin) and then, the size of the rectangular. Then, a Mid structure, which calculates the centre point of the rectangular. For some reason my function calc() doesn't want to return the values which it calculates and throws an error out of nowhere:

Cannot convert return expression of type '(Int, Int)' to return type 'Int"

Does anyone know why I get an error like that?

Swift code:

struct Point{
var x:Int, y:Int;
}

struct Sise{
var height:Int, width:Int;
}

struct Mid{
var origin:Point, sise:Sise;
func calc() -> Int{
var x = origin.x + (sise.width/2)
var y = origin.y + (sise.height/2)
return (x,y)
}
}

var origin = Point(x: 0,y: 0)
var sise = Sise(height:100, width:100)
var result = Mid(origin:origin,sise:sise)
result.calc()


NOTE

English is not my first language and sorry for the grammar mistakes.

Answer

In the struct Mid, you declare your function with return type is Int but in that function, you return a tuple (x,y). It must be:

struct Mid{
    var origin:Point, sise:Sise;
    func calc() -> (Int,Int) {
        var x = origin.x + (sise.width/2)
        var y = origin.y + (sise.height/2)
        return (x,y)
    }
}