简体   繁体   中英

Type 'String?' does not conform to protocol 'Equatable'

In my code below, the contents of winRankArray are all string objects. The issue I'm having is that setting the didWinRank variable at the end gives me the following error:

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

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?

        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. The standard library provides an implementation for !=.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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