OutputStream.init(toMemory: ())

I am trying to use the initializer for OutputStream with the signature init(toMemory: ()).

What is the "()"?

When I try to specify anything for the placeholder, I receive the warning, "Argument passed to call that takes no arguments"

So, how do I call this?

I think this API is being brought into swift incorrectly. In Objective-C this is a no arg init. But for some reason the Swift API is requiring void.

import Foundation

let a = OutputStream.init(toMemory: ())
var c = "hello".cString(using: .utf8)!.map(UInt8.init)

let len = a.write(&c, maxLength: c.count)
let out = a.property(forKey: .dataWrittenToMemoryStreamKey) as! Data

print(String(data: out, encoding: .utf8)!)

I prefer OutputStream.toMemory().

I found OutputStream.toMemory(). However, I was curious about the syntax, as I had never seen it before.

1 Like

I don't see this syntax in the Swift Programming Language document. I haven't ever seen it before, and it stumped me.

An empty tuple () is equal to Void in Swift. Regarding initializers have no name in Swift, and an argument must have type, they chose Void as argument type.

() is a zero-element tuple, so both the type and the value can be written (), as @nuclearace pointed out.

The general problem here is that this initializer takes no arguments, but still has semantic information that would get lost if imported as init(). The compromise the Swift compiler makes is to add a dummy parameter with empty tuple type, to save the rest of the method name. This could be important if someone wanted to subclass the class—it'd be different from just importing the initializer as a factory method. (Of course, you're free to use the factory method as well, as @amosavian brought up.)

EDIT: Heh, beat me to it. I'll leave mine here since there's slighly more explanation.


Thanks for the detailed explanation. It really clarifies what I'm looking at. It would be helpful if this was in the Swift Programming Language document.

It's mentioned briefly in "Functions Without Return Values" and "Tuple Types", but yeah, it could probably be a little more prominent. <-- @nnnnnnnn.

No mistake, the Swift Programming Language document is awesome. The only problem I have with it is all the wonderful nuggets buried here and there.

The info also shows up in Tuple Expressions.

Tuples are interesting because they're simple enough to show up in The Basics, but they're not complex enough to have their own chapter, so everything else about them shows up in the reference.

1 Like