尝试从闭包访问返回的字符串时出现编译器错误“无法将类型‘()’的返回表达式转换为返回类型‘String’”

问题描述 投票:0回答:1
func requestList(completionParameter: @escaping (String) -> String ) {
    let url = URL(string: "https://www.google.de")!
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        if let error = error {
            let message = error.localizedDescription
            completionParameter(message)
        }
        if let response = response {
            let message = response.mimeType!
            completionParameter(message)
        }
    }
    task.resume()
}

func printer() -> String {
    let dspmsg = requestList(completionParameter: { message1 -> String in
        let t = type(of: message1)
        print(t)
        return message1
        })
    return dspmsg

dspmsg
的返回值显然是
Void
,但是当我检查
message1
闭包内
completionParameter
的内容时,我总是得到预期的文本,并且它是
requestList类型
。在使用该
String
函数之前,我尝试直接打印闭包的返回值,这导致了同样的错误。
我的目标是请求网站数据并在关闭之外使用它。

我怀疑

printer()

中的返回发生在

printer()
完成之前。 但正如我所说,直接打印返回并规避计时问题,打印一个空元组,据我所知,它等于
completionParameter
    

swift closures urlsession
1个回答
0
投票

创建异步方法并使用 URLSession 异步方法

Void

data(from: URL)

将您的打印机方法也声明为异步:

func requestList() async throws -> String { let url = URL(string: "https://www.google.de")! let (_, response) = try await URLSession.shared.data(from: url) guard let mime = response.mimeType else { throw URLError(.unknown) } return mime }

然后你可以使用await来调用它

func printer() async throws -> String { let dspmsg = try await requestList() print(dspmsg) return dspmsg }

© www.soinside.com 2019 - 2024. All rights reserved.