我在我的代码中有一个“毁灭之塔”问题。
if places.count > 0 {
for i in 0..<places.count {
for j in 0..<places.count {
if let nameI = places[i]["name"] {
if let cityI = places[i]["city"] {
if let nameJ = places[j]["name"] {
if let cityJ = places[j]["city"] {
if let latI = places[i]["lat"] {
if let lonI = places[i]["lon"] {
if let latitudeI = Double(latI) {
if let longitudeI = Double(lonI) {
if let latJ = places[j]["lat"] {
if let lonJ = places[j]["lon"] {
if let latitudeJ = Double(latJ) {
if let longitudeJ = Double(lonJ) {
if(i != j) {
let coordinateI = CLLocation(latitude: latitudeI, longitude: longitudeI)
let coordinateJ = CLLocation(latitude: latitudeJ, longitude: longitudeJ)
let distanceInMeters = coordinateI.distance(from: coordinateJ) // result is in meters
let distanceInMiles = distanceInMeters/1609.344
var distances = [Distance]()
distances.append(Distance(
distanceInMiles: distanceInMiles,
distanceInMeters: distanceInMeters,
places: [
Place(name: nameI, city: cityI, lat: latitudeI, long: longitudeI, coordinate: coordinateI),
Place(name: nameJ, city: cityJ, lat: latitudeJ, long: longitudeJ, coordinate: coordinateJ),
]
))
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
我该如何避免这种情况?
有什么技巧或规则我应该遵循吗?
在iOS中,我们不得不使用大量的if-let
。有什么方法可以避免像我这样做?
Codable
,或者搜索一些开源解决方案,比如ObjectMapper
,用于 JSON 解析。 - pacification