@Published class 没有会员.store |结合 SwiftUI

@Published class has no member .store | Combine SwiftUI

正在尝试通过 Combine 解决里程碑中的挑战,但遇到错误:

Value of type 'Published<[User]>.Publisher' has no member 'store'

源代码:

import Combine
import Foundation


// MARK: Main model from API
struct User: Decodable, Identifiable {
    let id: UUID
    let isActive: Bool
    let name: String
    let age: Int
    let company: String
    let email: String
    let address: String
    let about: String
    let registered: Date
    let tags: [String]
    let friends: [Friend]
}

// MARK: - Friend array API
struct Friend: Decodable {
    let id: String
    let name: String
}


final class ViewModel: ObservableObject {
    @Published var model = [User]()

    private var subscriptions: Set<AnyCancellable> = []

    // Error: Value of type 'Published<[User]>.Publisher' has no member 'store'
    init() { $model.store(in: &subscriptions )}
}

extension ViewModel {
    // MARK: - Make request to API
    func fetch() -> AnyPublisher<User, Error> {
        guard let mainURL = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
            fatalError("404: Not found")
        }

        return URLSession.shared.dataTaskPublisher(for: mainURL)
            .map(\.data)
            .decode(type: User.self, decoder: JSONDecoder())
            .receive(on: RunLoop.main)
            .eraseToAnyPublisher()
    }
}

我不明白,我需要在哪里创建Publisher?

您的结构用户没有商店。因此,您正试图向您的结构添加不存在的内容。看看你的结构,那里没有商店:

struct User: Decodable, Identifiable {
    let id: UUID
    let isActive: Bool
    let name: String
    let age: Int
    let company: String
    let email: String
    let address: String
    let about: String
    let registered: Date
    let tags: [String]
    let friends: [Friend]
}

考虑到您的其他代码,这里是用法(使用 Xcode 11.4 编译)

init() {
  self.fetch()
    .sink(receiveCompletion: { _ in
        // do here whatever needed with error
    }, receiveValue: { [weak self] user in
        self?.model.append(user)
    })
    .store(in: &subscriptions)
}