How do I avoid pyramid of doom - iOS?

Viewed 1600

I have a pyramid of doom in my code.

enter image description here

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),
                                                                            ]
                                                                    ))
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

How do I avoid it?

Is there a technique or rule I should follow?

In iOS, we have to use a lot of if-let. How would one avoid doing like me ?

1 Answers

Here's a first approximation. As you can see, there are lots of repeated patterns that can be extracted out.

for (i, placeDictI) in 0..<places.enumerated() {
    guard
        let nameI = placeDictI["name"],
        let cityI = placeDictI["city"],
        let latitudeI = placeDictI["lat"].map(Double.init),
        let longitudeI =  placeDictI["lon"].map(Double.init),
        else { continue  }

        let coordinateI = CLLocation(latitude: latitudeI, longitude: longitudeI)
        let placeI = Place(name: nameI, city: cityI, lat: latitudeI, long: longitudeI, coordinate: coordinateI)

    for (j, placeDictJ) in places.enumerated() where i != j {
        guard  let nameJ = placeDictI["name"],
            let cityJ = placeDictI["city"],
            let latitudeJ = placeDictI["lat"].map(Double.init),
            let longitudeJ =  placeDictI["lon"].map(Double.init)
            else { continue }


        let coordinateJ = CLLocation(latitude: latitudeJ, longitude: longitudeJ)
        let placeJ = Place(name: nameJ, city: cityJ, lat: latitudeJ, long: longitudeJ, coordinate: coordinateJ)

        let distanceInMeters = coordinateI.distance(from: coordinateJ) // result is in meters // Editor's note: REALLY? I would have thought that a variable called "distanceInMeters" would store volume in litres! Silly me!
        let distanceInMiles = distanceInMeters/1609.344

        var distances = [Distance]()
        distances.append(Distance(
            distanceInMiles: distanceInMiles,
            distanceInMeters: distanceInMeters,
            places: [ placeI, placeJ ]
        ))
    }
}

Here are the transformations I applied:

  1. Don't check for places.count > 0. If it's 0, the loop won't do anything.
  2. For every if statement whose block fully encompasses its parent block, I replaced it with a guard.
  3. Merged adjacent guard statements with a comma.
  4. Expressed failable type conversions as Optional.map(_:) expressions, rather than as separate let clauses in the guard statement
  5. Changed the i != j check into a where condition on the inner for loop.
  6. Changed this pattern:

     for i in 0..<array.count {
         use(array[i])
         use(array[i])
         use(array[i])
         //...
     }
    

    to this pattern:

    for (i, element) in array.enumerated() {
         use(element)
         use(element)
         use(element)
         //...
     }
    

Seeing as there's no an obvious case of repetition, it's a good hint that the Dictionary unpacking into a Place belongs in a convenience initializer, that takes a dict that initailizes a Place? from it. Even better, just use the Codable system, and have the compiler synthesize it for you.

Related