Last active
April 12, 2022 14:49
-
-
Save damodarnamala/8af004a842c4e6aed8f09073ef52db78 to your computer and use it in GitHub Desktop.
Composing List with sorting options
This file contains hidden or 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
struct Country: Comparable, Identifiable { | |
static func < (lhs: Country, rhs: Country) -> Bool { | |
return lhs.name < rhs.name && lhs.code < rhs.code | |
} | |
var code: String | |
var name: String | |
var id = UUID() | |
} | |
let countries = [ | |
Country(code: "IN", name: "India"), | |
Country(code: "ID", name: "Indonesia"), | |
Country(code: "IL", name: "Israel"), | |
Country(code: "IQ", name: "Iraq"), | |
] | |
extension Array where Element == Country { | |
func sortByName() -> [Element] { self.sorted { $0.name < $1.name }} | |
func sortByCode() -> [Element] { self.sorted { $0.code < $1.code }} | |
func sortByNameAndCode() -> [Element] { self.sortByName().sortByCode() } | |
// also can do reversed | |
func sortByNameAndReversed() -> [Element] { sortByName().reversed()} | |
func sortByCodeAndReversed() -> [Element] { sortByCode().reversed()} | |
} | |
struct ContentView: View { | |
@State private var list = countries | |
var body: some View { | |
VStack(alignment: .center, spacing: 8) { | |
Text("Sort Options") | |
.foregroundColor(.brown) | |
.font(.headline) | |
Button( "By Name") { | |
list = list.sortByName() | |
} | |
Button("By Code") { | |
list = list.sortByCode() | |
} | |
Button( "By Name & Code") { | |
list = list.sortByName().sortByCode() | |
} | |
Button( "By Name & Reversed") { | |
list = list.sortByNameAndReversed() | |
} | |
} | |
List(list) { item in | |
SubtitledRow(data: (item.code, item.name)) | |
.onTapGesture { | |
dump(item) | |
} | |
} | |
} | |
} | |
struct SubtitledRow: View { | |
let data: (title:String, subtitle:String) | |
var body: some View { | |
HStack { | |
Text(data.title).font(.headline).foregroundColor(Color(.systemMint)) | |
Text(data.subtitle).font(.body).foregroundColor(.gray) | |
} | |
.padding(8) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated