简体   繁体   English

输入“字符串?” 不符合协议“平等”

[英]Type 'String?' does not conform to protocol 'Equatable'

In my code below, the contents of winRankArray are all string objects. 在下面的代码中, winRankArray的内容都是字符串对象。 The issue I'm having is that setting the didWinRank variable at the end gives me the following error: 我遇到的问题是,在最后设置didWinRank变量会给我以下错误:

Type 'String?' 输入“字符串?” does not conform to protocol 'Equatable' 不符合协议“平等”

I've tried removing ? 我尝试删除? so that setting card ranks looks like var cardRank1 = deckDictionary[cardKey1].first , but that gives me an error stating 所以设置卡的等级看起来像var cardRank1 = deckDictionary[cardKey1].first ,但这给了我一个错误

Value of optional type 'Array?' 可选类型“数组”的值 not unwrapped; 不展开 did you mean to use '!' 你是说用'!' or '?'? 要么 '?'?

How can I set the variables so that the resulting winRankArray doesn't have this problem? 如何设置变量,以使生成的winRankArray不会出现此问题?

        var cardKey1 = "card\(firstRandomNumber)"
        var cardRank1 = deckDictionary[cardKey1]?.first

        var cardKey2 = "card\(firstRandomNumber)"
        var cardRank2 = deckDictionary[cardKey2]?.first

        var cardKey3 = "card\(firstRandomNumber)"
        var cardRank3 = deckDictionary[cardKey3]?.first

        var cardKey4 = "card\(firstRandomNumber)"
        var cardRank4 = deckDictionary[cardKey4]?.first

        var cardKey5 = "card\(firstRandomNumber)"
        var cardRank5 = deckDictionary[cardKey5]?.first

        var cardKey6 = "card\(firstRandomNumber)"
        var cardRank6 = deckDictionary[cardKey6]?.first

        var cardKey7 = "card\(firstRandomNumber)"
        var cardRank7 = deckDictionary[cardKey7]?.first

        var winRankArray = [cardRank1, cardRank2, cardRank3, cardRank4, cardRank5, cardRank6, cardRank7]

        //func sameRank {loop through winRankArray, find 3 identical values, set winRankStatus to true}
        let didWinRank = winRankArray.slidingWindowWithLength(4).contains{ $0.allEqual() }

Type 'String?' 输入“字符串?” does not conform to protocol 'Equatable' 不符合协议“平等”

I don't think so ... 我不这么认为...

var s1: String? = "alfa"
var s2: String? = nil
var s3: String? = "beta"
var arr: Array<String?> = [s1, s2, s3]
arr.contains { (str) -> Bool in  // true
    str == "alfa"
}
s1 == "alfa" // true
s1 == s3     // false
s2 == nil    // true

When adopting Equatable, only the == operator is required to be implemented. 当采用Equatable时,仅需要实现==运算符。 The standard library provides an implementation for !=. 标准库提供了!=的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM