我有一个从我的 Firebase DB 获取数据并填充一些常量的结构,这是为了在单独的 VC 上填充 TabelView。最初我试图计算与 tableViewCell 类中位置的距离,但我希望能够按距离排序,并阅读有关计算结构内距离的内容。
所以我已将我的计算移至 struct asa func,并且我收到一条错误消息,指出在初始化所有存储的属性之前使用了“self”。
这是我的结构,我已经在出现错误的行上发表了评论。我在这里缺少什么?
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
]
}
}
最佳答案
你不能在初始化期间调用实例函数,要么将你的函数标记为static
(等于类函数),要么将其移动到另一个类/结构,或者尝试将函数移动到初始化方法中
关于ios - Struct 中的自初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42994875/