微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试使用 this NSHipster article中的一段示例代码,大约是页面的一半.

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,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",outputStream: &outputStream)

也就是说,它现在编译,但是没有运行,因为Nsstream显然没有getStreamsToHostWithName方法(至少在我导入的Foundation中)没关系,这是一个仅限iOS的调用,所以它不能用于游乐场设置为OSX.它设置为iOS似乎没问题.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐