@Published类没有成员.store |结合SwiftUI

时间:2020-04-14 12:40:36

标签: swift swiftui combine

试图通过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()
    }
}

我不明白,我需要在哪里创建发布者?

2 个答案:

答案 0 :(得分:1)

考虑到您的其他代码,以下是用法(与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)
}

答案 1 :(得分:0)

您的结构用户没有存储。因此,您正在尝试向您的结构中添加不存在的内容。看看您的结构,那里没有存储:

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]
}