arrays - 类型 'Bool' 不符合协议(protocol) 'Sequence'

标签 arrays swift for-in-loop

我几周前开始学习 Swift,在一节课(数组和 for .. in 循环)中,我必须制作一个计算选票并给出答案的函数。

所以我编写这段代码时认为就是这样,但出现此错误 -> “Type 'Bool' does not conform to protocol 'Sequence'”

代码如下:

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"
}

错误在第 4 行出现“withVotes”

已经有一些数组获得了 Bool 类型的值。

最佳答案

欢迎学习 Swift!您偶然发现了编译器正确的地方,但作为初学者,它并不总是很明显。

在这种情况下,虽然它指出第 4 行是问题所在,但这不是您需要修复的地方。您需要找到问题的源头,在本例中是第 1 行,这里...

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

特别是 withVotes: Bool。问题是因为你写的方式,它只允许你传入一个 bool 值。根据您的问题和其余代码,您显然想传入几个。

为此,只需将其设为 bool 数组,如下所示... withVotes: [Bool](注意方括号。)

这是您更新后的代码,在第 1 行而不是第 4 行进行了更改。请注意,如果您愿意,我还更新了签名和变量名称,使其更加“快速”:

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"
}

希望这能解释得更多一些,再次欢迎来到 Swift 大家庭! :)

关于arrays - 类型 'Bool' 不符合协议(protocol) 'Sequence',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49329412/

相关文章:

swift - Swift Playground 中的数据值变化

javascript - 我可以在 Angular 模型中使用 for ... in 语法吗?

javascript - 只使用一次数组元素

c - 使用 sprintf、C 填充字符串

python - 定位并切掉数据数组中的重叠部分

ios - 如何检查 Firebase 权限是否被拒绝?

Swift:按身份查找数组

java - 在 Java 中是否可以有一个包含数组和基元的数组?

arrays - Int类型不符合协议(protocol)顺序

javascript - 循环javascript的解释