user3284547
user3284547

Reputation: 105

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

Upvotes: 0

Views: 3378

Answers (3)

Paulw11
Paulw11

Reputation: 114975

You can access a slice of your original set as follows:

let slice = indexSet[indexSet.indexRange(in: 3...13)]

slice accesses the existing elements in place, so creation of the slice is O(1)

Upvotes: 0

rmaddy
rmaddy

Reputation: 318874

One possible solution is to use a filter to create a new IndexSet.

let set = IndexSet(arrayLiteral: 1,2,3,5,6,7,13,31)
let subset = set.filteredIndexSet { (index) -> Bool in
    index >= 3 && index <= 13
}

Upvotes: 0

Alexander
Alexander

Reputation: 63341

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]

Upvotes: 2

Related Questions