无法使用类型为 'Int' 的参数列表调用初始值设定项 '(format: String, Double)'



我想保存一个距离(来自两个位置(作为一个数字(Int(,以便能够按这个数字对tableViewCells进行排序...

我试图像这样保存距离:

static var takenLocation: Int?
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lastLocation = locations.last {
let geocoder = CLGeocoder()
//get job coordinates
geocoder.geocodeAddressString(job.location) { placemarks, error in
//get user coordinates
let myLocation = CLLocation(latitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude)
//get distance between coordinates
let distance = myLocation.distance(from: jobLocation) / 1000
print(String(format: "The distance to the Job is %.01fkm", distance))
JobTableViewCell.takenLocation = Int(format: "%.01km", distance) -> ERROR
}
}
}

但是通过这个,我得到无法调用类型"Int"的初始值设定项,参数列表类型为"(格式:字符串,双精度(">作为错误...... 我该如何解决这个问题?或者有没有另一种方法可以将距离保存为数字?

编辑:

struct sortJobs {
let sDistance = JobTableViewCell.takenLocation
}
var sJobs = [sortJobs]()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.sJobs.sort(by: { ($0.sDistance) < ($1.sDistance) }) -> ERROR
self.tableView.reloadData()
})
}

我现在得到二元运算符"<"不能应用于两个"Int?"操作数,并且无法将类型为"字符串"的值转换为预期的参数类型"Int">作为错误

Int 没有这样的初始化器。从代码中,您将takenLocation声明为 Int。

所以你可能想使用:

JobTableViewCell.takenLocation = Int(distance)

或者,您将 takenLocation 声明为字符串并将代码更改为:

static var takenLocation: String?
JobTableViewCell.takenLocation = String(format: "%.01fkm", distance)

很可能是一个错字(实际上是两个(。

Int没有format初始值设定项,从格式说明符中,您显然想要一个字符串表示形式,其中包含一个小数位的Double

,这是"%.1f"
static var takenLocation: String?
JobTableViewCell.takenLocation = String(format: "%.1fkm", distance)

整数没有小数位(也没有字母😉(。如果要保存Double的整数部分,可以写入

static var takenLocation: Int? // Consider to declare the variable as non-optional takenLocation = 0
JobTableViewCell.takenLocation = Int(round(distance))

最新更新