Search code examples
arraysswiftfor-in-loop

Type 'Bool' does not conform to protocol 'Sequence'


I started learning Swift few weeks ago and in one lesson (Arrays and for .. in loops) I had to make func that counts votes and gives an answer.

So I made this code thinking thats it but this error pops in -> "Type 'Bool' does not conform to protocol 'Sequence'"

here's the code:

func printResults(forIssue: String, withVotes: Bool) -> String {
    positive = 0
    negative = 0
    for votes in withVotes {
        if votes == true {
            positive += 1
        } else {
            negative += 1
        }
    }
    return "\(forIssue) \(positive) yes, \(negative) no"
}

The error pops in 4th line with 'withVotes'

There are already some arrays that got Bool type values.


Solution

  • Welcome to learning Swift! You've stumbled across something where the compiler is right, but as a beginner, it's not always evident on what's going on.

    In this case, although it's pointing to line 4 as the problem, that's not where you need to fix it. You need to go to the source of the problem, which in this case is line 1, here...

    func printResults(forIssue: String, withVotes: Bool) -> String {
    

    Specifically withVotes: Bool. The problem is because of the way you have it written, it's only allowing you to pass in a single boolean. By your question and the rest of your code, you clearly want to pass in several.

    To do that, simply make it a bool array, like this... withVotes: [Bool] (Note the square brackets.)

    Here's your updated code with the change on line 1, not line 4. Note I also updated the signature and variable names to be more 'swifty' if you will where the focus should always be on clarity:

    func getFormattedResults(for issue: String, withVotes allVotes: [Bool]) -> String {
    
        var yesVotes = 0
        var noVotes  = 0
    
        for vote in allVotes {
            if vote {
                yesVotes += 1
            }
            else {
                noVotes += 1
            }
        }
    
        return "\(issue) \(yesVotes) yes, \(noVotes) no"
    }
    

    Hope this explains it a little more, and again, welcome to the Swift family! :)