簡體   English   中英

類型“布爾”不符合協議“序列”

[英]Type 'Bool' does not conform to protocol 'Sequence'

我幾周前開始學習Swift,在一堂課(數組和for .. in循環)中,我不得不做些能計算票數並給出答案的函數。

因此,我使這段代碼以為是這樣,但是此錯誤在->“類型'Bool'不符合協議'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 問題是由於您編寫的方式,它只允許您傳遞單個布爾值。 通過您的問題和其余代碼,您顯然希望傳遞幾個。

為此,只需將其設置為布爾數組,例如... 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家族! :)

編譯器是正確的。 您正在嘗試使用withVotes遍歷bool值。

解決方案是創建布爾值數組。 像下面

for i in [true, false, true] {
    if i == true { print("true") }

}

withVotes的參數從Bool更改為[Bool] ,編譯器會很高興:)

最后,可能看起來像

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

您需要像這樣傳遞一個數組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM