Swift 无法将表达式的类型“Void”转换为类型“String!”

2024-05-27

我正在尝试使用一段示例代码这篇 NSHipster 文章 http://nshipster.com/ios8/,大约在页面的中间位置。

var inputStream: NSInputStream
var outputStream: NSOutputStream

NSStream.getStreamsToHostWithName(hostname: "nshipster.com",
                                      port: 5432,
                               inputStream: &inputStream,
                              outputStream: &outputStream)

我把它和import Foundation,我收到此错误。

Playground execution failed: error: <REPL>:6:10: error: cannot convert the expression's type 'Void' to type 'String!'
NSStream.getStreamsToHostWithName(hostname: "nshipster.com",
~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

这个错误指向第一个参数,它的类型显然是String!并不是Void.

我对代码进行了一些更改,以从方法调用中提取定义。这是完整的游乐场:

import Foundation

var inputStream: NSInputStream
var outputStream: NSOutputStream

let host = "nshipster.com"
let port = 5432
NSStream.getStreamsToHostWithName(hostname: host,
    port: port,
    inputStream: &inputStream,
    outputStream: &outputStream)

现在错误指示第三个参数,大概对前两个参数满意。

Playground execution failed: error: <REPL>:10:18: error: cannot convert the expression's type 'Void' to type 'inout NSInputStream'
inputStream: &inputStream,
             ^~~~~~~~~~~~

我不知道如何提取AutoreleasingUnsafePointerinputStream 和 outputStream 的变量以相同的方式,但我认为原始示例代码应该可以工作。这是我(和 Mattt)代码中的错误,还是 Swift 中的错误?

EDIT: 我已经提交了拉取请求 https://github.com/NSHipster/articles/pull/174以及 NSHipster 的更正代码。


好吧,简短的答案是,您需要传递可选值而不是非可选值(对于任何正在寻找 inout 对象的东西)

var inputStream:NSInputStream?
var outputStream:NSOutputStream?

NSStream.getStreamsToHostWithName("nshipster.com", port: 5432, inputStream: &inputStream, outputStream: &outputStream)

也就是说,它现在可以编译,但不能运行,因为 NSStream 显然没有 getStreamsToHostWithName 方法(至少在我导入的 Foundation 中),没关系,这是一个仅限 iOS 的调用,所以它不能与Playground 设置为 OSX。看来设置成iOS就可以了。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift 无法将表达式的类型“Void”转换为类型“String!” 的相关文章

随机推荐