본문 바로가기

iOS/Swift

Swift Hashable Protocol

 

ForEach는 식별 가능한 항목의 컬렉션을 반복하는 데 사용됩니다. 이를 위해 항목이 고유하게 식별될 수 있어야 합니다. 
Hashable 프로토콜을 준수하면 Swift가 자동으로 Equatable도 준수하게 됩니다. 이는 MatchingList 구조체의 인스턴스를 고유하게 식별할 수 있도록 합니다.

 

 

import SwiftUI

 

struct MatchingList: Hashable{

    let title: String

    let titleNum: String

}

 

struct ListView: View {

    

    var titleDataModel = [

        MatchingList(title: "ㄱ", titleNum: "ㄴ"),

        MatchingList(title: "ㄷ", titleNum: "ㄹ"),

        MatchingList(title: "ㅁ", titleNum: "ㅂ"),

        MatchingList(title: "ㅅ", titleNum: "ㅇ"),

        MatchingList(title: "ㅈ", titleNum: "ㅊ"),

        MatchingList(title: "ㅋ", titleNum: "ㅌ")

    ]

    

    var body: some View {

        NavigationStack{

            List {

                ForEach(titleDataModel, id: \.self) {name in

                    HStack{

                        Text(name.title)

                        Spacer()

                        Image(systemName: "arrow.right")

                    }

                }

            

                

            } //List

            .navigationTitle("Title")

        } //NavigationStack

    } //body

} //ListView

 

 

 

#Preview {

    ListView()

}

'iOS > Swift' 카테고리의 다른 글

Swift List 사용해보기  (0) 2024.07.09
Swift Stat 와 Binding  (0) 2024.07.08
Swift Day_11  (0) 2024.07.06
Switft Day_10  (0) 2024.07.06
Swift Day_09  (0) 2024.07.06