SwiftUI-如何及何時使用Equatable and Identifiable protocols

LULU
彼得潘的 Swift iOS App 開發教室
4 min readMay 16, 2022

--

內個..如果有中英參雜的部分請多包涵><我實在不確定如何用我的口語來翻譯比較正確, 所以還是請大家直接看英文

  1. Equatable protocols 可以比較相同類型的instances, 可以使用“==”比較是否相等, 也可以使用 “!=”比較value的不相等

2. Identifiable protocols 適用於任何“需要穩定自我的身份”
(原文:The Identifiable protocol is for use with any type that needs to have a stable notion of identity.)
唯一的要求是需要 ”id”, 讓他自己決定 id 是什麼型別, 同時須符合 Hashbale 的協議

以下範例是我在做翻牌遊戲一部分的 code 之後會再放上完整的

struct Card: Identifiable {
var isFaceUp: Bool = false
var isMatched: Bool = false
var content: CardContent
var id: Int
}

以struct 定義 Card 的 model, 並讓每一張卡都有獨特的id, 因此使用 Identifiable protocol
後面因為需要由程式判斷兩張卡的內容是否為相同的,所以使用Equatable procotol

struct MemoryGame<CardContent> where CardContent: Equatable {
private(set) var cards: Array<Card>

private var indexOfTheOneAndOnlyFaceUpCard: Int?

mutating func choose(_ card: Card) {
if let chosenIndex = cards.firstIndex(where: {$0.id == card.id}),
!cards[chosenIndex].isFaceUp,
!cards[chosenIndex].isMatched {

if let potentailMatchIndex = indexOfTheOneAndOnlyFaceUpCard {
if cards[chosenIndex].content == cards[potentailMatchIndex].content {
cards[chosenIndex].isMatched = true
cards[potentailMatchIndex].isMatched = true
}
indexOfTheOneAndOnlyFaceUpCard = nil
} else {
for index in cards.indices {
cards[index].isFaceUp = false
}
indexOfTheOneAndOnlyFaceUpCard = chosenIndex
}
cards[chosenIndex].isFaceUp.toggle()
}
}
}

參考文章:

--

--

LULU
彼得潘的 Swift iOS App 開發教室

Hi👋 I’m iOS developer, I hope I can grow with you guys ☺️ Let’s learn more together.