Search code examples
iosarraysswifttextview

How can I shuffle text in a Text View?


Hey I'm a beginner in Swift and I created a Text View with text and now I want that when I click on the button the text shuffles. First I worked with shuffle() but it can only shuffles text in Arrays. The problem is that text every time could be different. So I can't make an fixed Array. I also tried to make an empty Array and set it on the text, but it failed. How can I shuffle the text in the Text View?


Solution

  • Certainly not the most elegant version but it does what you want it to do: (Tested on iOS 13.5)

    struct ContentView: View {
        
        @State var text = "There will be text"
    
        
        var body: some View {
            VStack() {
                
                Text(self.text)
                
                Button(action: {
                    // new empty array. Could also be outside
                    var arr: Array<String> = []
    
                    //Split current text at every space
                    for s in self.text.split(separator: " ") { 
                        arr.append(String(s)) //append to new array
    
                        // if length of new array is the length of all substrings
                        if arr.count == self.text.split(separator: " ").count {
                            arr.shuffle()
                            self.text = "" // empty Text field
                            for s in arr {
                                self.text.append(s + " ")
                            }
                        }
                    }
                }){
                    Text("Button")
                }
            }
        }
        
    }