匹配卡片和表情符号。有我不明白的事情。它正在生成两张相同的卡。当两个卡的标识符相同时,我不明白它如何获得相同的表情符号。我不了解func emoji
的行为。查看结果部分显示的内容。
当两个标识符相同时,它不会调用该函数:
import Foundation
struct Card {
var isFaceUp = false
var isMatched = false
var identifier: Int
static var identifierFactory = 0
static func getUniqueIdentifer() -> Int {
identifierFactory += 1
return identifierFactory
}
init() {
self.identifier = Card.getUniqueIdentifer()
}
}
var cards = Array<Card>()
for _ in 1...6 {
let card = Card()
cards += [card, card]
}
for card in cards {
print("card \(card)")
}
var emojiChoices = ["", "", "", "", "", "⏳", "☕︎", "", "☪️", "", "", ""]
var emoji = [Int: String]()
func emoji(for card: Card) -> String {
print("Card Id: \(card.identifier)")
if emoji[card.identifier] == nil {
let randomIndex = Int(arc4random_uniform(UInt32(emojiChoices.count)))
print("RandomIndex \(randomIndex)")
print("In Card Id: \(card.identifier)")
emoji[card.identifier] = emojiChoices.remove(at: randomIndex )
print("id \(emoji[card.identifier] )")
}
return emoji[card.identifier] ?? "?"
}
var card = cards[0]
var emo1 = emoji(for: card)
print("emo1 \(emo1)")
card = cards[4]
var emo2 = emoji(for: card)
print("emo2 \(emo2)")
card = cards[2]
var emo3 = emoji(for: card)
card = cards[3]
var emo4 = emoji(for: card)
print("\(emo1) , \(emo2), \(emo3) and \(emo4)")
结果:
Card Id: 1
RandomIndex 4
In Card Id: 1
id Optional("")
emo1
Card Id: 3
RandomIndex 1
In Card Id: 3
id Optional("")
emo2
Card Id: 2
RandomIndex 1
In Card Id: 2
id Optional("")
Card Id: 2
, , and
答案 0 :(得分:2)
您很困惑,最后两张牌都是蝴蝶()。
此循环:
Expression<Func<T, bool>> predicate
正在将成对的卡片添加到for _ in 1...6 {
let card = Card()
cards += [card, card]
}
阵列中。因此,cards
和card[0]
相同(具有相同的card[1]
),identifier
和card[2]
相同,并且card[3]
和card[4]
相同。
因此,最后要打印card[5]
,card[0]
,card[4]
和card[2]
。由于card[3]
和card[2]
具有相同的card[3]
,因此两者将显示相同的identifier
。
emoji
如何为相同的标识符返回相同的表情符号?
func emoji
正在填充func emoji
字典。该词典是从卡emoji
到表情符号字符的映射。如果卡片标识符已在词典中,则它将返回其中的值。如果这是第一次访问标识符,它将从identifier
数组中获取一个新的随机表情符号字符,并使用卡emojiChoices
作为密钥将其添加到字典中。
用相同的标识符重复调用identifier
将返回相同的表情符号字符,因为该值将在func emoji
字典中找到。
如果您在每次调用emoji
之后打印emoji
字典,它将帮助您了解正在发生的事情:
func emoji
输出:
var card = cards[0] var emo1 = emoji(for: card) print("emoji dict is now \(emoji)") print("emo1 \(emo1)") card = cards[4] var emo2 = emoji(for: card) print("emoji dict is now \(emoji)") print("emo2 \(emo2)") card = cards[2] var emo3 = emoji(for: card) print("emoji dict is now \(emoji)") card = cards[3] var emo4 = emoji(for: card) print("emoji dict is now \(emoji)") print("\(emo1) , \(emo2), \(emo3) and \(emo4)")