⭐️custom Model 커스텀 모델/ Identifiable⭐️
구조체, 클래스와 같은 커스텀 타입은 관련된 속성, 메서드들을 모아서 사용하는데 의의가 있음을 기억하자.
이 예시를 보면 리스트 안에 셀에 정보(속성)가 굉장히 많이 들어있다.
닉네임, 이름, 팔로워수, 온라인상태여부, 검증여부 등..
따라서 해당 속성들을 묶어서 새로운 모델을 만들어 보자.
// Created by Toughie on 2023/05/02.
//
import SwiftUI
//다양한 속성을 담기 위한 커스텀 모델
struct UserModel: Identifiable {
var id: String = UUID().uuidString
let nickName: String
let userName: String
let follower: Int
let isVerified: Bool
var isOnline: Bool
}
struct ModelPrac: View {
//커스텀 모델을 활용해 객체를 배열로 관리
@State var users: [UserModel] = [
// "Toughie", "Jones", "Jason", "Shapiro"
UserModel(nickName: "Power", userName: "Toughie", follower: 777, isVerified: true, isOnline: true),
UserModel(nickName: "HAX", userName: "Jones", follower: 34, isVerified: false, isOnline: true),
UserModel(nickName: "JD", userName: "Jason", follower: 152, isVerified: true, isOnline: false),
UserModel(nickName: "ATG", userName: "Shapiro", follower: 125, isVerified: true, isOnline: true)
]
var body: some View {
NavigationView {
List {
ForEach(users) { user in
HStack(spacing: 20) {
Circle()
.frame(width: 20, height: 20)
.foregroundColor(user.isOnline ? .green : .red)
VStack(alignment: .leading) {
Text(user.nickName)
.font(.headline)
Text("@\(user.userName)")
.foregroundColor(.gray)
.font(.caption)
}
Spacer()
if user.isVerified {
Image(systemName: "checkmark.seal.fill")
.foregroundColor(.blue)
}
VStack {
Text("\(user.follower)")
.font(.headline)
Text("Followers")
.foregroundColor(.gray)
.font(.caption)
}
}
.padding(.vertical, 10)
}
// ForEach(users, id: \.self) { user in
// HStack(spacing: 20) {
// Circle()
// .frame(width: 20, height: 20)
// Text(user.nickName)
// }
// .padding(.vertical, 10)
//
// }
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("ToughStargram")
}
}
}
Identifiable
- 데이터 모델의 식별자(identifier)를 정의.
이 프로토콜을 준수하는 데이터 모델은 'id'라는 이름의 고유한 식별자를 가져야함.
ex. Swift에서 List를 사용할 때 id를 구현해야 하고, 이를 통해 List에서 특정 항목을 식별할 수 있음.
(List 뷰는 데이터 소스를 표시하기 위한 컨테이너뷰, 여러 개의 항목을 스크롤 가능한 목록으로 표시 가능)
-> 각 항목을 구별하기 위해 각각의 고유한 식별자가 필요, 목록 업데이트/ 항목 추가/삭제/이동의 경우에 특히 중요함.
UUID
- 범용 고유 식별자(Universally Unique Identifier)를 생성하는 데 사용되는 클래스.
무작위로 생성된 128비트의 값으로 이루어진 고유한 식별자를 생성함.
UUID는 대규모 분산 시스템에서 객체를 식별하거나, DB에서 고유한 키를 생성하는 등의 상황에서 유용함.
'SwiftUI > SwiftUI(Basic)' 카테고리의 다른 글
[51] @EnvironmentObject / 뷰 계층 구조 (0) | 2023.05.07 |
---|---|
[50] @Publisehd, @StateObject, @ObservedObject / MVVM (0) | 2023.05.07 |
48. [SwiftUI] .onTapGesture() 탭 제스쳐 (0) | 2023.05.02 |
47. [SwiftUI] Optional Unwrapping( if let / guard let ) (0) | 2023.05.02 |
46. [SwiftUI] .onAppear/disappear & DispatchQueue, 동시성 프로그래밍/ 비동기적 실행 (0) | 2023.05.02 |