Search code examples
swiftnsindexset

Trying to access some elements in an IndexSet


I'm using IndexSet and I'm trying to access some indexes which at times are consecutive and at other times are not.

For example, my set may contain [1, 2, 3, 5, 6, 7, 13, 31]

I want to pull out of the set a range of 3...13, but am having difficulty with the syntax. I've learned how to use the function commands from Apple documentation, by using myIndexSet.sorted(). However, the Apple Documentation does not give an example of how to access a range of elements in the set. The Apple Documentation for accessing elements in the index set are the following:

subscript(Range<IndexSet.Index>)

I've tried a number of ways to write this but can't figure out how to do it right. Can someone show me how to access a range of elements in the set to create a new set? I've tried things such as:

let subset = subscript(Range: myLargerSet.3...13)

but it doesn't seem to work.

Thanks


Solution

  • What you're looking for is the intersection of your IndexSet ([1, 2, 3, 5, 6, 7, 13, 31]) with another IndexSet ([3, 4, ..., 12, 13]):

    let yourIndexSet: IndexSet = [1, 2, 3, 5, 6, 7, 13, 31]
    let desiredIndexRange = IndexSet(3...13)
    let indicesOfInterest = yourIndexSet.intersection(desiredIndexRange)
    print(indicesOfInterest.sorted()) // => [3, 5, 6, 7, 13]