1

Find object value at index and store it in a different array using swift.

Can someone tell me the most optimized way for the following code snippet

    var selectedIndex = [1,3,5]
    var allData : [Person] = []
    var ids: [Int] = []
    for (index, item) in allData.enumerated() {
        for id in selectedIndex {
            if id == index {
                ids.append(item.id)
            }
        }
    }
2
  • 1
    "the most optimized way"? ids = [allData[1].id,allData[3].id,allData[5].id] Commented Oct 14, 2020 at 14:32
  • 1
    @JoakimDanielson Nothing wrong asking how to optimize his code. As it is he is unnecessarily iterating all elements in his collection. Commented Oct 14, 2020 at 14:53

2 Answers 2

3

If you are sure that all indices are valid you can simply map your selected indices:

let ids = selectedIndex.map { 
    allData[$0].id
}

If you want to make sure the selected index exists in allData:

let ids = selectedIndex.compactMap {
    allData.indices ~= $0 ? allData[$0].id : nil
}
Sign up to request clarification or add additional context in comments.

Comments

0

Because your indices are sorted, you can take just the portion of allData that you need, using prefix.

let ids =
  allData
  .prefix(selectedIndices.last.map { $0 + 1 } ?? 0)
  .enumerated()
  .compactMap {
    Optional($0)
      .filter { selectedIndices.contains($0.offset) }?
      .element.id
  }
public extension Optional {
  /// Transform `.some` into `.none`, if a condition fails.
  /// - Parameters:
  ///   - isSome: The condition that will result in `nil`, when evaluated to `false`.
  func filter(_ isSome: (Wrapped) throws -> Bool) rethrows -> Self {
    try flatMap { try isSome($0) ? $0 : nil }
  }
}

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.