在放大代码片段的范围内找不到类型“AnyCancellable”

Joe*_*vis 13 swift graphql aws-amplify swiftui

import Foundation
import SwiftUI
import Amplify


class MovesAPI: ObservableObject {
    
    
    @Published var todoLIst: [MoveType?] = [nil]
    
    
    init() {
        listTodos()
    }
    
    func listTodos() -> AnyCancellable { //cannot find type 'AnyCancellable' in scope
        let moveType = MoveType.keys
        let sink = Amplify.API.query(request: .paginatedList(MoveType.self)) //Generic parameter 'R' could not be inferred //Type 'GraphQLRequest<_>' has no member 'paginatedList'
            .resultPublisher
            .sink {
                if case let .failure(error) = $0 {
                    print("Got failed event with error \(error)")
                }
            }
            receiveValue: { result in
            switch result {
                case .success(let todos):
                    print("Successfully retrieved list of todos: \(todos)")
                case .failure(let error):
                    print("Got failed result with \(error.errorDescription)")
                }
            }
        return sink
    }

}

Run Code Online (Sandbox Code Playgroud)

最终我的目标是从 amplify GraphQL API 获取 MoveType 类型的所有模型。这是直接粘贴到我的项目中的代码片段,我收到这些类型错误。知道为什么吗?从 amplify,文档(https://docs.amplify.aws/lib/graphqlapi/query-data/q/platform/ios#query-by-id)我所做的就是更改模型名称以匹配我的后端并删除查询参数。

小智 28

我认为你需要:

import Combine
Run Code Online (Sandbox Code Playgroud)


Joe*_*vis 0

好的,它工作了,只需变得更简单,我使用组合模式关闭

import Foundation
import SwiftUI
import Amplify


class MovesAPI: ObservableObject {
    
    
    @Published var todoLIst: [MoveType?] = [nil]
    
    
    init() {
    }
    
    func listTodos() {
        print("listing todos")
    
        Amplify.API.query(request: .list(MoveType.self)) { event in
            switch event {
               case .success(let result):
                   switch result {
                   case .success(let todos):
                       print("Successfully retrieved list of todos: \(todos)")
                   case .failure(let error):
                       print("Got failed result with \(error.errorDescription)")
                   }
               case .failure(let error):
                   print("Got failed event with error \(error)")
               }
           }
    
    }

}
Run Code Online (Sandbox Code Playgroud)

不过,如果有人知道为什么 amplify 文档中的代码片段不起作用,我很想知道。