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:
```
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
}
Thanx!
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
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?
I tried a slightly different solution that dealt with the question of changing the return type:
func findAll<T: Equatable, S: Collection>(_ collection: S, _ element: T) -> [S.Index] where S.Element == T {
var indexes = [S.Index]()
var i = collection.startIndex
while i != collection.endIndex {
if collection[i] == element {
indexes.append(i)
}
i = collection.index(after: i)
}
return indexes
}
var strArray = findAll("StringTest", "t") // [{_rawBits 65793}, {_rawBits 590081}]
print("StringTest"[strArray[0]]) // t
let str2 = ["A", "AB", "ABC", "A"]
print(findAll(str2, "A")) // [0, 3]