D. Finna D. Finna - 1 month ago 8
iOS Question

Counting end value of multiple arrays - swift

I have a hard time finding out how to count the ending value of multiple arrays. Let me give you an example:

Here I have four arrays:

let numberOne: [string] = ["...", "...", "car"]
let numberTwo: [string] = ["...", "...", "bike"]
let numberThree: [string] = ["...", "...", "car"]
let numberFour: [string] = ["...", "...", "car"]


Lets say those are my arrays. I do not know, however, how many arrays there are each time, can be between 1 and 14.

How do I show a count for how many arrays there is containing an ending value of, for instance,
car
?

Hope you can help me :-)

Answer

One way:

func countLastEelement(){
    let numberOne: [String] = ["...", "...", "car"]
    let numberTwo: [String] = ["...", "...", "bike"]
    let numberThree: [String] = ["...", "...", "car"]
    let numberFour: [String] = ["...", "...", "car"]

    let numbers:[[String]] = [numberOne, numberTwo, numberThree, numberFour]

    var count:Int! = 0

    for number in numbers {
        if number[number.count-1] == "car" {
            count = count + 1
        }
    }
    print(count) // output: 3
}

Another:

for number in numbers {
    if number.last == "car"{
        count = count + 1
    }
}
Comments