Home > Enterprise >  SwiftUI I'd like to get a text from the console
SwiftUI I'd like to get a text from the console

Time:11-02

VStack {

.onAppear {
                
                for cont in contactsVM.contacts {
                    
                    info = "\(cont.firstName) \(cont.lastName);\(cont.phone);//"
                    
                }
                
            }
}

If you save the text in the info and print it out, only one text comes out

enter image description here

I want to get all the text that appears on the console

I'm going to take it and use it as a text editor

CodePudding user response:

You overwrite info in each iteration of the loop so eventually it contains the data of the last item of the array.

Rather than with a loop you could map the data and convert the array to string (paragraphs) with joined(separator:)

VStack {
    .onAppear {
        info = contactsVM.contacts.map{"\($0.firstName) \($0.lastName);\($0.phone);//"}.joined(separator: "\n")         
    }
}

CodePudding user response:

When you are running the for loop , with every iteration the value of info is changing to a new value. This is the reason you are seeing only one value.

use this instead.

        var info = ""
        for contact in contactsVM.contacts {
            info.append("\(cont.firstName) \(cont.lastName);\(cont.phone) \n")
        }
  • Related