Ch. 21, Generics, Gold Challenge

   func findAll<T: Collection, U: Equatable>(_ collection: T, _ item: U) -> [Int] where T.Element == U {
      var findedIndexes = [Int]()
      
        for (index, element) in collection.enumerated() {
            if element == item {
                  findedIndexes.append(index)
            }
        }
        return findedIndexes
    }

Your code looks prettier if you enclose it with a pair of three back-tick characters (```) like this: :slight_smile:
```
Code
```

func findAll <T: Collection, U: Equatable> (_ collection: T, _ item: U) -> [Int] where T.Element == U {
  var foundIndexes = [Int]()
  
    for (index, element) in collection.enumerated () {
        if element == item {
           foundIndexes.append (index)
        }
    }
    return foundIndexes
}


1 Like

Thanx! :slight_smile:

Hi @mgmzlm,
I saw that you use enumerated method from Collection protocol.
How do you hear about this method?

Good bye!

I read Apple documentation on Collection and Sequence.

The developer documentation from Xcode or from the website?

They are same in content.

Ok :upside_down_face:

1 Like

How do you hear about this method?

I read Apple documentation on Collection and Sequence.

Here’s my solution for the Gold Challenge

func findAll<C: Collection, T: Equatable>(_ collection: C, _ element: T) -> some Collection {
    var positions = [T]()
    for (i, item) in collection.enumerated() where item as! T == element {
        positions.append(i as! T)
    }
    return positions
}

findAll([5,3,7,3,9], 3)    //[1, 3]

However, I’m not sure if I satisfied the requirements to change the return type from [Int] to an array of an associated type of the Collection Protocol. Can someone give me some feedback?