我正在尝试使用 this NSHipster article中的一段示例代码,大约是页面的一半. var inputStream: NSInputStreamvar outputStream: NSOutputStreamNSStream.getStreamsToHostWithName(hostname: "nshipster.com", port: 5432, inputStrea
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类型!而不是虚空.
我稍微更改了代码,从方法调用中提取定义.这是完整的游乐场:
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, ^~~~~~~~~~~~
我无法弄清楚如何以相同的方式为inputStream和outputStream提取AutoreleasingUnsafePointer变量,但我认为原始的示例代码应该可行.这是我(和Mattt的)代码中的错误,还是Swift中的错误?
编辑:我已经提交了一份带有更正NSHipster代码的pull request.
好吧,简短的回答是你需要传递选项而不是非选项(对于任何寻找inout对象的东西)var inputStream:NSInputStream? var outputStream:NSOutputStream? NSStream.getStreamsToHostWithName("nshipster.com", port: 5432, inputStream: &inputStream, outputStream: &outputStream)
也就是说,它现在编译,但是没有运行,因为NSStream显然没有getStreamsToHostWithName方法(至少在我导入的Foundation中)没关系,这是一个仅限iOS的调用,所以它不能用于游乐场设置为OSX.它设置为iOS似乎没问题.