ios - Struct 中的自初始化错误

标签 ios swift xcode

我有一个从我的 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/

相关文章:

iphone - 如何将触摸标签文本传递给手势识别器选择器方法

ios - 在其父类(super class)初始化之后初始化 UIView init?

ios - 如何在没有 Mac Developer 程序成员(member)资格的情况下使用 NSLogger Desktop Client

ios - 在 xcode 6.1 和 os x yosemite 中不支持 ios 7.1 及以下版本?

ios - 在类函数中通过关键字 `self` 初始化泛型类

ios - 如何获得 UIFont 的 preferedFontForTextStyle 的粗体版本?

ios - UIKit Dynamics 通过碰撞更改 View 框架

swift - 快速搜索带有圆角半径的栏

ios - UITableView 部分之间的空间是多少?

iphone - xcode,nslog 奇怪的问题