组合代码片段在功能上不起作用,我该如何让它工作

Combine snippet not working in function, how do I get this to work

我有两段代码,都很相似。

一个在操场上工作,表现符合预期。

另一个,当我使它成为函数的一部分时(在 Xcode 项目中)不起作用,Xcode 的一个非常明显的警告是 'immutable value of cancellableSink was never used'

当我在操场上执行这段代码时,我没有收到 Xcode 的警告。怎么回事?

我感觉我的问题不在于 Combine,而是更根本的问题

import Foundation
import Combine


let url = URL(string: "https://xkcd.com/614/info.0.json")



let publisher = URLSession.shared.dataTaskPublisher(for: url!)
    .map{ [=10=].data }
    .decode(type: Joke.self, decoder: JSONDecoder())
    .map { [=10=].img}

let cancellableSink = publisher
    .sink(receiveCompletion: { completion in
        print(String(describing: completion))
    }, receiveValue: { value in
        print("Returned value: \(value)")
    })

上面的代码片段可以在 playground 中运行 ..但是为什么这不能在函数内部的 Xcode proj 中运行。

下面是一个警告,我将进入一个我无法在 playgrounds 中重复的 Xcode 项目

你在函数中创建了let cancellableSink,所以它的范围仅限于这个函数。 cancellableSink 将在您离开 myCompletionHandler 后立即释放。

相反,尝试在 class / 结构级别声明 cancellableSink,这样它会在 函数完成后保留。