Cook Kim
Cook Kim

Reputation: 37

Why Swift Set fucntion Why firstIndex(of: ) Apply?

I understand Set Collection is key-value and Keys are not duplicated.

In the example below, I thought fruits were the key.

however .firstIndex(of: ) is exist why?

So can a second index exist?

Am I misunderstanding the set?

var favoriteFruits: Set = ["Banana", "Apple", "Orange", "Orange"]

favoriteFruits.insert("WaterMelon")
print(favoriteFruits)
favoriteFruits.remove("Banana")
print(favoriteFruits)

if favoriteFruits.contains("Tomato") {
    print("Tomato is my favorite Fruits")
} else {
    print("Tomato is not my favorite Fruits")
}

print(favoriteFruits.firstIndex(of: "Orange"))

It would be of great help if you leave a comment.

Upvotes: 2

Views: 150

Answers (2)

Sweeper
Sweeper

Reputation: 272865

This is a consequence of Set<String> conforming to Collection<String>. The Collection protocol requires this method:

func firstIndex(of element: Self.Element) -> Self.Index?

The associated types Element and Index are also required by the Collection protocol. Even if Set is not index-based, Set does declare a nested struct called Index. See its implementation here.

It is true that there can be no "second" index for a particular element, since elements in a set are unique. firstIndex(of:) and lastIndex(of:) for any element for a set would return the same thing.

However, the Collection protocol does not care. After all, functions that can take any Collection does not know what kind of collection they are working with, e.g.

func someGenericFunction<C: Collection>(collection: C) {
    // ...
}

so they need to specify whether they want the first, last, or the nth index of a particular element, so that their code works for all kinds of collections. If Set did not have these methods, then Set is not a Collection, and cannot be passed to these functions.

Upvotes: 1

Omer Tekbiyik
Omer Tekbiyik

Reputation: 4764

If you check firstIndexOf method's explanition you will see a defition :

Available when Element conforms to Equatable.

Sets conforms to Equatable.You can also test this while checking the equality of the two sets.Below code doesn't give any error.

if set1 == set2{
  //....
}

You ask .firstIndex(of: ) is exist why?

So there is no obstacle for the collection type of Set to use the firstIndexOf method

If you ask why set is equatable.Set uses the hash table to check the elements inside. So the Set must be hashable.An object that conforms to Hashable must also be Equatable too

Upvotes: 1

Related Questions