THIS IS ELLIE

스위프트 Identifiable 프로토콜 본문

개발/Swift

스위프트 Identifiable 프로토콜

Ellie Kim 2020. 6. 16. 19:20

스탠퍼드 대학의 강의를 학습하면서 Identifiable프로토콜을 사용하길래 궁금해진 Identifiable 프로토콜 🤔

 

그래서 오늘은 Identifiable 프로토콜에 대해서 살펴보겠습니다.

https://developer.apple.com/documentation/swift/identifiable

저는 이 친구를 처음 보았는데요.

이 프로토콜은 5.1에 구현되었다고 합니다.

 

한마디로 말하자면 Indentifiable프로토콜은 식별 가능하게 하는 프로토콜입니다.

이 프로토콜이 어떻게 이뤄져 있는지 살펴보겠습니다.

associatedtype으로 ID가 선언되어 있습니다.

그리고 이는 Hashable을 준수합니다.

Hashable프로토콜을 준수하기 때문에 hashValue를 갖게 됩니다.

이 hashValue는 각 인스턴스를 식별 가능하도록 합니다.

 

예를 들어서

카드 매칭 하는 게임을 만든다고 해봅시다.

카드를 매칭 하기 게임을 만들기 위해서 카드 구조체를 만들고 안에는 4가지 변수들을 생성해줍니다.

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

게임에서 필요한 카드들을 가지고 있을 구조체 MemoryGame을 선언해줍니다.

struct MemoryGame<CardContent> {
    var cards: Array<Card>    
    
    init(numberOfPairsOfCards: Int, cardContentFactory: (Int) -> CardContent) {
        // create empty array
        cards = Array<Card>()
        
        // for loop with iteratable thing (0..<numberOfPairsOfCards)
        for pairIndex in 0..<numberOfPairsOfCards {
            let content: CardContent = cardContentFactory(pairIndex)
            cards.append(Card(content: content, id: pairIndex * 2))
            cards.append(Card(content: content, id: pairIndex * 2 + 1))
        }
    }
}

그리고 각 카드 구조체를 초기화하는 부분입니다.

0부터 numberOfPairsOfCards까지 루프를 돌면서 두 개씩 카드 구조체를 초기화해줍니다.

(짝 맞추는 게임이니 두개씩 카드를 만들어 줍니다)

(만약 numberOfPairsOfCards을 3으로 설정하면 짝을 3개로 설정한 것이기 때문에 총 6개의 카드가 생성됩니다)

(초기화할 때 isFaceUp, isMatched는 초기값이 존재하기 때문에, content와 id만 작성해 줍니다)

 

그리고 카드를 선택하면 choose메서드를 통해 어떤 카드를 선택했는지 확인하는 작업이 필요합니다.

mutating func choose(card: Card) {
    print("card chosen: \(card)")
    if let chosenIndex: Int = self.index(of: card) {
        self.cards[chosenIndex].isFaceUp = !self.cards[chosenIndex].isFaceUp
    }
}

func index(of card: Card) -> Int? {
    for index in 0..<self.cards.count {
        if self.cards[index].id == card.id {
            return index
        }
    }
    return nil
}

어떤 카드를 선택했는지 확인하기 위해 카드에 Identifiable프로토콜을 선언했습니다.

Identifiable프로토콜을 선언했기 때문에 id를 프로퍼티를 선언해 값을 설정해줬습니다.

즉 카드 구조체는 id를 통해 각 카드를 식별할 수 있게 됩니다. 

 

코드 : 

struct MemoryGame<CardContent> {
    var cards: Array<Card>    
    
    init(numberOfPairsOfCards: Int, cardContentFactory: (Int) -> CardContent) {
        // create empty array
        cards = Array<Card>()
        
        // for loop with iteratable thing (0..<numberOfPairsOfCards)
        for pairIndex in 0..<numberOfPairsOfCards {
            let content: CardContent = cardContentFactory(pairIndex)
            cards.append(Card(content: content, id: pairIndex * 2))
            cards.append(Card(content: content, id: pairIndex * 2 + 1))
        }
    }
    
    mutating func choose(card: Card) {
        print("card chosen: \(card)")
        if let chosenIndex: Int = self.index(of: card) {
            self.cards[chosenIndex].isFaceUp = !self.cards[chosenIndex].isFaceUp
        }
    }
    
    func index(of card: Card) -> Int? {
        for index in 0..<self.cards.count {
            if self.cards[index].id == card.id {
                return index
            }
        }
        return nil
    }
    
    // structure free initialize
    // nested struct
    struct Card: Identifiable {
        var isFaceUp: Bool = false
        var isMatched: Bool = false
        var content: CardContent
        var id: Int
    }
}

 

코드 출처: 스탠퍼드 강의

 

https://developer.apple.com/documentation/swift/identifiable

 

Identifiable - Swift Standard Library | Apple Developer Documentation

The collection of underlying identified data that SwiftUI uses to create views dynamically.

developer.apple.com

https://developer.apple.com/documentation/swift/hashable

 

Hashable - Swift Standard Library | Apple Developer Documentation

Conforms when Base conforms to Collection, Base.Element conforms to Collection, Base.Index conforms to Hashable, and Base.Element.Index conforms to Hashable.

developer.apple.com

 

반응형

'개발 > Swift' 카테고리의 다른 글

스위프트 비트 연산자  (0) 2020.09.18
dropFirst(_:), removeFirst(_:) 살펴보기  (1) 2020.09.16
스위프트 클래스  (0) 2020.05.30
스위프트 인터뷰  (0) 2020.05.30
스위프트5.0 Result타입  (0) 2020.04.01