将对象数组映射到另一个数组且 Combine 不起作用?

Map array of objects into another array with Combine not working?

我在我的视图模型中订阅了一个@Published 数组,这样我就可以将每个附加的对象映射为一个 PostAnnotations 数组...

我无法将 post 数组映射到 PostAnnotations 数组并得到错误:

错误消息:声明的闭包结果“()”不兼容

我做错了什么??

class UserViewModel: ObservableObject {
    var subscriptions = Set<AnyCancellable>()
    let newPostAnnotationPublisher = PassthroughSubject<[PostAnnotation], Never>()

    @Published var currentUsersPosts: [Posts] = []
  
    func addCurrentUsersPostsSubscriber() {
        $currentUsersPosts
             // convert each post into a PostAnnotation
            .map { posts -> [PostAnnotation] in
                 // ^ERROR MESSAGE: Declared closure result '()' is incompatible 
                //with contextual type '[SpotAnnotation]'
                posts.forEach { post in
                    let postAnnotation = PostAnnotation(post: post)
                    return postAnnotation
                }
            }
            .sink { [weak self] postAnnotations in
                guard let self = self else { return }
                // send the array of posts to all subscribers to process
                self.newPostAnnotationsPublisher.send(postAnnotations)
            }
            .store(in: &subscriptions)
    }

     func loadCurrentUsersPosts() {
         PostApi.loadCurrentUsersPosts { response in
             switch response {
             case .success(let posts):
                 self.currentUsersPosts.append(contentsOf: spots)
             case .failure(let error):
                 //////
             }
         }
     }

}

forEach 没有 return 值。您想要 map,其中 return 是一个基于闭包内部执行的转换的新集合:

.map { posts -> [PostAnnotation] in
    posts.map { post in
        let postAnnotation = PostAnnotation(post: post)
        return postAnnotation
    }
}

或者,更短:

.map { posts -> [PostAnnotation] in
    posts.map(PostAnnotation.init)
}

而且,甚至更短(尽管我认为它此时开始失去可读性):

.map { [=12=].map(PostAnnotation.init) }