Swift中for循环内的字典访问

时间:2014-06-10 16:37:25

标签: dictionary swift

我试图在Swift中做几个PoC - 我的第一个实验是一个简单的纸牌游戏。

我在尝试在for循环中访问字典时遇到了问题:

let suits: Array<String> = ["Spades", "Diamonds", "Clubs", "Hearts"]
let ranks: Array<Integer> = [1,2,3,4,5,6,7,8,9,10,11,12,13]
let rankMap: Dictionary<Int,String> = [1:"Ace", 11:"Jack", 12:"Queen", 13:"King"]

struct Card {
    let suit: String
    let rank: Integer
    let image: String? //There's some NSObject that corresponds to image resources. Later.
}

func buildDeck(NumberOfJokers:Int) -> Array<Card>{
    assert(NumberOfJokers <= 2, "Can't have more than two jokers in a deck")
    var retDeck: Array<Card> = []
    for s in suits {
        for r in ranks {
            let newSuit = rankMap[r]? //ERROR: Could not find an overload for subscript that accepts the supplied arguments
            retDeck.append(Card(suit:s, rank:r, image: nil))

        }
    }

    return retDeck
}

我无法弄清楚如何在循环通过r数组时使用ranks的当前值作为标识符从{{1}中拉出正确的字符串}字典。我可以尝试使用rankMap整数作为字典键抛出这个&#34;无法找到过载&#34;消息。

我知道我会从rankMap中获得一个Optional,但是unwrapping / chaining方法不会产生任何不同的结果。

1 个答案:

答案 0 :(得分:2)

问题是你的数组持有Integers并且你的字典使用Ints作为键。更改数组以保留Ints!关于basic section of the docs中的不同类型,有一些说明。

// was using Integer so now use Int
let ranks: Array<Int> = [1,2,3,4,5,6,7,8,9,10,11,12,13]

// is keyed with Int
let rankMap: Dictionary<Int,String> = [1:"Ace", 11:"Jack", 12:"Queen", 13:"King"]

// hence your problem.

以下是一个显示问题的简单示例:

var b: Integer = 3
var c: Int = 5
let bc = b + c // throws error!