Created
May 15, 2024 16:37
-
-
Save kean/39f6217b437c21a0347825f6cb60530d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// search-test | |
// | |
// Created by Alex on 5/15/24. | |
// | |
import SwiftUI | |
import SwiftUI | |
struct Name: Identifiable { | |
let id = UUID() | |
let firstName: String | |
} | |
struct ContentView: View { | |
@State private var searchText = "" | |
let names: [Name] = [ | |
Name(firstName: "Alice"), | |
Name(firstName: "Bob"), | |
Name(firstName: "Charlie"), | |
Name(firstName: "David"), | |
Name(firstName: "Edward"), | |
Name(firstName: "Fiona"), | |
Name(firstName: "George"), | |
Name(firstName: "Hannah"), | |
Name(firstName: "Irene"), | |
Name(firstName: "Jack"), | |
Name(firstName: "Karen"), | |
Name(firstName: "Larry"), | |
Name(firstName: "Mona"), | |
Name(firstName: "Nancy"), | |
Name(firstName: "Oscar"), | |
Name(firstName: "Paul"), | |
Name(firstName: "Quincy"), | |
Name(firstName: "Rachel"), | |
Name(firstName: "Sam"), | |
Name(firstName: "Tina"), | |
Name(firstName: "Uma"), | |
Name(firstName: "Victor"), | |
Name(firstName: "Wendy"), | |
Name(firstName: "Xander"), | |
Name(firstName: "Yvonne"), | |
Name(firstName: "Zack") | |
] | |
var filteredNames: [Name] { | |
if searchText.isEmpty { | |
return names | |
} else { | |
return names.filter { $0.firstName.lowercased().contains(searchText.lowercased()) } | |
} | |
} | |
var groupedNames: [String: [Name]] { | |
Dictionary(grouping: filteredNames) { name in | |
String(name.firstName.prefix(1)) | |
} | |
} | |
var body: some View { | |
NavigationView { | |
List { | |
ForEach(groupedNames.keys.sorted(), id: \.self) { key in | |
Section(header: Text(key)) { | |
ForEach(groupedNames[key] ?? []) { name in | |
Text(name.firstName) | |
} | |
} | |
} | |
} | |
.listStyle(.grouped) | |
.navigationBarTitle("Names") | |
.searchable(text: $searchText) | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment