Resolved: Toggle work automatically inside the button

Question:

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?

Answer:

It does not really work logically.
Basically, your array movies always occurs reverse() 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.

If you have better answer, please add a comment about this, thank you!

If you like this answer, you can give me a coffee by <a href=”https://violencegloss.com/mkw7pgdwwr?key=2a96ade6f3760c7e63343a320febb78e”>click here</a>

Source: Stackoverflow.com