wjl
wjl

Reputation: 7361

Swift cannot convert the expression's type 'Void' to type 'String!'

I'm trying to use a piece of sample code from this NSHipster article, about halfway down the page.

var inputStream: NSInputStream
var outputStream: NSOutputStream

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

I've placed this in a playground, along with import Foundation, and I get this error.

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

This error is pointing to the first argument, which is clearly of type String! and not Void.

I changed the code up a bit, to extract the definitions from the method call. Here's the complete playground:

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)

Now the error indicates the third argument, presumably happy with the first two.

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

I can't figure out how I can extract AutoreleasingUnsafePointer variables for inputStream and outputStream in the same manner, but I think the original sample code should work. Is this a bug in my (and Mattt's) code, or a bug in Swift?

EDIT: I've submitted a pull request with the corrected code for NSHipster.

Upvotes: 4

Views: 3912

Answers (1)

David Berry
David Berry

Reputation: 41226

Well, the short answer is that you need to be passing in optionals instead of non-optionals (to anything that's looking for inout objects)

var inputStream:NSInputStream?
var outputStream:NSOutputStream?

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

That said, it compiles now, but doesn't run because NSStream apparently doesn't have a getStreamsToHostWithName method (at least in the Foundation I get imported) Never mind this, it's an iOS-only call, so it didn't work with Playground set to OSX. Seems to be ok with it set to iOS.

Upvotes: 7

Related Questions