在Struct

时间:2017-03-24 08:40:33

标签: ios swift xcode

我有一个从我的Firebase数据库获取数据并填充一些常量的结构,这是在一个单独的VC上填充TabelView。最初我试图计算tableViewCell类中的位置距离,但我希望能够按距离排序,并阅读有关计算结构中距离的内容。

所以我已经将我的计算结果移动到结构asa func,我收到一个错误声明自己'在所有存储的属性被初始化之前使用。

这是我的结构,我评论了出现错误的行。我在这里缺少什么?

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
    ]

 }

}

1 个答案:

答案 0 :(得分:1)

在初始化期间无法调用实例函数,可以标记函数static(等于类函数)或将其移动到另一个类/结构,或者尝试在初始化方法中移动函数