Bronze Challenge
Generics are probably the most abstract part about Swift so far for me, so it took me a little longer than normal to wrap my head around them. Here’s my filter function for the Bronze challenge:
struct Stack<Element>: Sequence {
...
func filter(_ f: (Element) -> Bool) -> Stack<Element> {
var filteredItems = Stack<Element>()
for item in items {
if f(item) == true {
filteredItems.push(item)
}
}
return filteredItems
}
}
var filteredStack = myStack.filter({ $0 == 1 })
for value in filteredStack {
print("Filtered stack values: \(value)")
}
Silver Challenge
This one is kind-of straightforward. Create the findAll(_:_:)
function with the challenge speifications, making sure to make it generic:
func findAll<T: Equatable>(_ array: [T], _ elementToFind: T) -> [Int] {
var positions = [Int]()
for (index, item) in array.enumerated() {
if item == elementToFind {
positions.append(index)
}
}
return positions
}
findAll([5,3,7,3,9], 3) // returns [1, 3]
findAll(["hey", "what", "thats", "what", "hey"], "hey") // returns [0, 4]
Gold Challenge
This one is really going over my head. I feel like I am so close to the solution for this, however nothing I’m doing is compiling. If anyone has the solution for this, please share!