Int, String 등의 배열은 .sorted()
를 통해 자동으로 정렬할 수 있다. 그러나 Struct 같은 경우는 아래 코드처럼 어떤 속성을 기준으로 어떻게 정렬할 건지 설정해주어야 한다.
struct Person: Identifiable {
let id = UUID()
var firstName: String
var lastName: String
}
struct ContentView: View {
let people = [
Person(firstName: "철수", lastName: "팽"),
Person(firstName: "지현", lastName: "선우"),
Person(firstName: "민수", lastName: "제갈")
].sorted {
$0.lastName < $1.lastName
}
var body: some View {
List(people) { person in
Text("\(person.lastName) \(person.firstName)")
}
}
}
혹은 operator overloading을 통해 Person
이 <
에 어떻게 적용되는지 설정해서 .sorted()
적용 시에 설정한 대로 정렬된다.
struct Person: Comparable, Identifiable {
let id = UUID()
var firstName: String
var lastName: String
static func <(lhs: Person, rhs: Person) -> Bool {
lhs.lastName < rhs.lastName
}
}
💡 lhs
(left hand sight), rhs
는 마음대로 설정할 수 있다.
Swift로 UserDefaults나 SwiftData를 통해 데이터를 작성하고 읽고 수정하고 삭제할 수 있다. 그러나 이 방식들은 시스템이 데이터를 어디에 어떻게 저장해서 개발자가 관여할 수 없다.
Swift로 직접 데이터를 작성하고 읽는 방법으로는 Data를 만들고, 그 데이터를 지정한 경로(url)에 저장되도록 하고, 그 경로에서 다시 읽어 오는 방법이 있다.
struct ContentView: View {
var body: some View {
Button("Write and Read the data") {
let data = Data("Test Data".utf8)
let url = URL.documentsDirectory.appending(path: "message.txt")
do {
try data.write(to: url, options: [.atomic, .completeFileProtection])
let input = try String(contentsOf: url)
print(input)
} catch {
print(error.localizedDescription)
}
}
}
}
예시로 로딩 전, 로딩 중, 로딩 완료, 로딩 실패라는 상태가 있고, 각 상태에 따라 다른 View를 보여준다. 이때 enum을 통해서 상태를 인식하고 변경하면 편하다.
enum LoadingState {
case before
case loading
case success
case failed
}
struct ContentView: View {
@State private var loadingState = LoadingState.before
var body: some View {
switch loadingState {
case .before:
BeforeView()
case .loading:
LoadingView()
case .success:
SuccessView()
case .failed:
FailedView()
}
}
}
// ...