1

I want to better understand recursive looping and flatten in Swift or any other language for that matter.

I have a simple Swift class


class Survey { 
      let items: [SurveyItem]?
}

class SurveyItem { 
      let id: String?
      let items: [SurveyItem]?
}

A Survey has items and each item can have more types of its own.

I want to write a function which assembles all items and subitems in a survey into a single flat array

1
  • 1
    I would avoid using nullable collections. Just model empty case with an empty collection. Commented May 23, 2019 at 19:24

1 Answer 1

7
protocol SurveyItemVending {
    var items: [SurveyItem]? { get }
}

extension Survey: SurveyItemVending { }
extension SurveyItem: SurveyItemVending { }

extension SurveyItemVending {
    var allItemsRecursively: [SurveyItem] {
        let items = self.items ?? []
        return items + items.flatMap { $0.allItemsRecursively }
    }
}

Now you can ask any Survey or SurveyItem for its allItemsRecursively.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.