I have a struct that gets data from my Firebase DB and populate a number of constants, this is to populate a TabelView on a seperate VC. initially I was trying to calculate distance from location in the tableViewCell class, but I want to be able to sort by distance, and read something about calculating the distance within the struct.
So I have moved my calculation to the struct asa func, and I am getting an error stating 'self' used before all stored properties are initialzed.
This is my struct and I have commented on the line where the error appears. What am I missing here?
import Foundation
import FirebaseDatabase
import CoreLocation
struct newTracks {
//Declerations
var locationManager = CLLocationManager()
let name: String!
let lat: Double!
let lon: Double!
let countryImage: String!
let link: String!
let ref: FIRDatabaseReference?
let distance: Double
//Initialize
init(name: String, trackId: Int, postcode: String, trackType: String, trackURL: String, locID: Int, lat: Double, lon: Double, phoneNumber: String, email: String, rating: Double, numrating: Double, totalrating: Double, countryImage: String, link: String, distance: Double) {
self.name = name
self.ref = nil
self.lat = lat
self.lon = lon
self.countryImage = countryImage
self.link = link
self.distance = distance
}
//Initialize data from Firebase
init(snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: AnyObject]
name = snapshotValue["name"] as! String
lat = snapshotValue["lat"]as! Double
lon = snapshotValue["long"]as! Double
ref = snapshot.ref
countryImage = snapshotValue["country"] as! String
link = snapshotValue["link"] as! String
distance = getDistance() //error on this line -- 'self' used before all stored properties are initialzed
}
//calculate distance from current location to destination location
func getDistance() -> CLLocationDistance {
let currentLat = self.locationManager.location!.coordinate.latitude
let currentLon = self.locationManager.location!.coordinate.longitude
let myLocation = CLLocation(latitude: currentLat, longitude: currentLon)
let loc = CLLocation(latitude: self.lat, longitude: self.lon)
let distanceInMiles = round(myLocation.distance(from: loc) / 1609.34)
return distanceInMiles
}
func toAnyObject() -> Any {
return [
"name": name,
"lat": lat,
"lon": lon,
"countryImage": countryImage,
"link": link,
"distance": distance
]
}
}