Silver Challenge - partial solution?


#1

I’ve been working on this challenge for days… with maybe some success, but I can not figure out how to automatically switch if you input Int vs. Strings. I’d love to see a real fix :sunglasses: Comments show one try.

func findAll<T: Equatable, U: Equatable>(_ A1: [T], _ B1: (U)) -> [Int] {

var result = [Int]()
var counter = 0
let tB = type(of: B1)
print(" tB = \(tB)")

for _ in A1 {

// if tB as! String == “String” {
// print(“It’s a String”)
// let lhs:String = B1 as! String
// let rhs:String = A1[counter] as! String
// } else {
// print(“it’s not a String”)
let lhs:Int = B1 as! Int
let rhs:Int = A1[counter] as! Int
// }

    if (lhs == rhs) {
        result.append(counter)
        print("match found")
    } else {
        print("not matched")
    }
    //         print("A1 counter = \(A1[counter]) " )
    //         print("result = \(result)")
    
    counter += 1
}
print(" \nMatches at these indicies: \(result)")
return result

}

let answer = findAll([5,3,7,3,9], 3)
//let answer = findAll([“fish”,“turkey”, “duck” ,“turtle” ,“duck”], “duck”)
//findAll([“fish”,“turkey”, “duck” ,“turtle” ,“duck”], “duck”)


#2
func findAll<T: Equatable, U: Equatable>(_ A1: [T], _ B1: (U))  -> [Int] {

var result = [Int]()
var counter = 0
let tB = type(of: B1)
print(" tB = \(tB)")

for _ in A1 {
    let lhs:Int = B1 as! Int
    let rhs:Int = A1[counter] as! Int
    
    if (lhs == rhs) {
        result.append(counter)
        print("match found")
    } else {
        print("not matched")
    }
    counter += 1
}
print(" \nMatches at these indicies: \(result)")
return result }

#3

It looks to me like you may have included too many generic elements in your function. You only need to look at Elements of type T.This is the solution I came up with:

func findAll<T: Equatable>(_ items: [T], keyItem: T) -> [Int] {
    var foundItems = [Int]()
    var index = 0

    for item in items {
        if item == keyItem {
            foundItems.append(index)
        }
        index += 1
    }
    
    return foundItems
}