Reputation: 35
My code seems to crash due to an infinite loop, but I can't find the error. Could someone help me out and look over the code?
Here is my controller:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let location = touch.location(in: self.view)
let x = Float(location.x)
let y = Float(location.y)
let newTouch = Touch(latitude: x,longitude: y)
TouchService().addTouch(touch: newTouch, grid: _grid)
}
}
And my model:
import Foundation
class Touch {
var _lat: Float
var _long: Float
var _startingPoint: Touch
init(latitude lat: Float, longitude long: Float){
self._lat = lat
self._long = long
self._startingPoint = Touch(latitude: lat, longitude: long)
}
}
I guess there is something wrong with the way I am using the init() function.
Kind regards and thanks in advance, Chris
Upvotes: 0
Views: 44
Reputation: 1862
Your initializer creates an infinite loop.
//Touch(latitude: lat, longitude: long) calls the initializer again.
//Since you are inside the initializer, it creates an infinite loop.
self._startingPoint = Touch(latitude: lat, longitude: long)
Comment that out and you'll see.
Create a separate class or struct for your values (composition).
class AngularLocation {
var _lat: Float
var _long: Float
and
class Touch {
var destination: AngularLocation
var startingPoint: AngularLocation
Tweak that to your needs.
Upvotes: 1
Reputation: 9503
This is how your code is working
class Touch {
var _lat: Float
var _long: Float
var _startingPoint: Touch
init(latitude lat: Float, longitude long: Float){
self._lat = lat
self._long = long
self._startingPoint = Touch(latitude: lat, longitude: long) // It invokes recursively your Touch class with no end, so it causes infinite loop
}
}
Solution
You have to create different class for StartingPoint
.
Upvotes: 0