Search code examples
swiftlistviewswiftuiswiftui-list

From userDefaults.standard.sring(forKey "name").components(seperatedby: " ") I want to make a List


From userDefaults.standard.sring(forKey "name").components(seperatedby: " ") I want to make a List in a View (SwiftUI List). List { userDefaults.standard.string(forKey "name").components(seperatedby: " ")[1] userDefaults.standard.string(forKey "name").components(seperatedby: " ")[2] ... } with a variable length of userDefaults.standard.string(forKey "name").components(seperatedby: " "

I tried for...in and while but it can't be in a View


Solution

  • First of all you need to fetch data from the UserDefaults and after that build a List. Here you can find more info about List component in SwiftUI: https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-a-list-of-dynamic-items

    Also you can't place String inside the List, you should wrap it by Text component (here is info about this component https://developer.apple.com/documentation/swiftui/text)

    So this is how it should look like in your case:

    struct ContentView: View {
        // Extracting data from UserDefaults
        let names = UserDefaults.standard.string(forKey: "name")?.components(separatedBy: " ") ?? []
        
        var body: some View {
            // List received array of names by first parameter
            List(names, id:\.self) { name in
                Text(name) // <-- Here you wrap your string inside UI component
            }
        }
    }
    

    But you should know that this list won't be dynamic. If something will be changed inside UserDefaults, your view won't be updated. For making it dynamic you should create an ObservableObject model for managing your data. You can read more about this protocol on this link: https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-observedobject-to-manage-state-from-external-objects