输入'String?'不符合协议'Equatable'

时间:2015-10-29 04:18:08

标签: arrays swift

在我的下面的代码中,winRankArray的内容都是字符串对象。我遇到的问题是在最后设置didWinRank变量会给我以下错误:

  

输入'String?'不符合协议'Equatable'

我已尝试删除?,以便设置卡片排名看起来像var cardRank1 = deckDictionary[cardKey1].first,但这会给我一个错误说明

  

可选类型'数组'的值?没有打开;你的意思是用'!'还是'?'?

如何设置变量以便生成的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() }

1 个答案:

答案 0 :(得分:0)

  

输入'String?'不符合协议'Equatable'

我不这么认为......

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
  

采用Equatable时,只需要==运算符   实现。标准库提供了!=。

的实现