struct MoviesShow: View {
@State var movies: [String] = [
"Peaky",
"JW 3",
"Shwan RDS",
"The Last Air Bender",
"JW 2",
"Spider Man 3",
"The Great Wall",
"Avatar",
"Dragon",
"My Love for Tiger",
"Cinderella",
"Nobody",
"Scarface"
]
@State var isAZ: Bool = false
var body: some View {
ScrollViewReader { r in
ScrollView {
Button("Sorted By") {
if isAZ {
movies.sort()
}
else {
movies.reverse()
}
}
ForEach(movies, id: .self) { movie in
Text(movie)
.font(.system(size: 35))
}
}
}
}
}
If you look closely my button don’t have isAZ.toggle() inside meaning isAZ == false always. For some how this Button still work? Every time I click the order of sort change but the value of isAZ == false?
2
Answers
It does not really work logically.
Basically, your array
movies
always occursreverse()
which means it keeps reversing itself back and fourth.Say you have: [Z, B, C]. Every time you press the button, this array occurs
reverse()
-> [C, B, Z] -> [Z, B, C] -> [C, B, Z] -> [Z, B, C].However, it's not really sorting your elements properly as it should. You still need some other conditions handle because your input data was not sorted in the first place.
Each time you tap the button you do reverse so it seems to work but actually just reverse the order each time.