Idan Aviv Idan Aviv - 1 month ago 6
Swift Question

Swift class object sends its value when calling a function

I have a function inside a class that need to get the value of the object and then return a different value. I want to do something like what apple do with CLLocation distance. Where you can call

point1.distance(point2)


where the value of both point1 and point2 are sent.

I know I could create a function and send the parameter in the function like this:

getDistance(point1: Location, point2: Location)


Is there is any way to use the more elegant style the function and how its being called, like the way Apple uses their fucntions.

Answer

you can do something like this:

class Location {

private var _position: Double!

var position: Double {
    return _position
}

init(position: Double) {

    self._position = position
}

func distance (reference: Location) -> Double {
    let point1 = self.position //or whatever leads to your value
    let point2 = reference.position
    //do what ever you have to do with both points e.g.
    let result = point1 - point2
    return result
}

}

let point1 = Location(position: 50.0)

let point2 = Location(position: 32.0)

now you can do your desired thing:

point1.distance(reference: point2)

// returns 18
Comments