2

I started playing with SwiftUI in the last few days and it makes a lot of sense. However, I'm struggling when it comes to updating a persisting list.

I'm using UserDefaults and JSONEncoder.

struct ContentView: View {

    private var slackController = Slack()

    @EnvironmentObject var userData: UserData

    var body: some View {
        return NavigationView {
            List {
                ForEach(self.userData.statuses) { myStatus in
                    HStack {
                       // row code
                    }
                    .onTapGesture {
                        self.slackController.setStatus(text: myStatus.description, emoji: myStatus.emoji)
                    }
                }
                .onDelete(perform: delete)
            }
        }
    }

    func delete(at offsets: IndexSet) {
        self.userData.statuses.remove(atOffsets: offsets)
    }

Both insert and delete are working, because when I relaunch the app I can see the changes.

private let defaultStatuses: [Status] = [
    Status(emoji: ":spiral_calendar_pad:", description: "In a meeting", expireHours: 1),
    Status(emoji: ":car:", description: "Commuting", expireHours: 12),
]

final class UserData: ObservableObject {
    let didChange = PassthroughSubject<UserData, Never>()

    @UserDefault(key: "ApiToken", defaultValue: "")
    var apiToken: String {
        didSet {
            didChange.send(self)
        }
    }

    @UserDefault(key: "Statuses", defaultValue: defaultStatuses)
    var statuses: [Status] {
        didSet {
            didChange.send(self)
        }
    }
}

I can see that didChange.send(self) is called, but I can't figure out why the list isn't updated.

The code is also in a repo in case I've missed something from the example that is useful. I've also been using SwiftUITodo to try figure out I'm doing wrong.

Any help/guideance would be appreciated.

João Colaço
  • 1,202
  • 1
  • 14
  • 38
Daniel P
  • 2,439
  • 3
  • 20
  • 27
  • 3
    There have been some changes to how Combine works. Look [here] (https://sarunw.com/posts/swiftui-changes-in-xcode-11-beta-5) to look at the changes. – 39fredy Sep 21 '19 at 07:05
  • I couldn't see anything more than a few variable name changes. Also didSet to willSet. It seems the issue might be that I'm using \@UserDefault and not \@Published, but I can't see how to combine them. – Daniel P Sep 21 '19 at 11:32
  • Actually, that seems to be all it was! Thanks. – Daniel P Sep 21 '19 at 11:40
  • Glad that worked ! – 39fredy Sep 21 '19 at 16:00

0 Answers0