Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active August 29, 2015 14:02
Show Gist options
  • Save kristopherjohnson/ed4d1969efe0fd2f8542 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/ed4d1969efe0fd2f8542 to your computer and use it in GitHub Desktop.
C++-style stream output for Swift. (For fun only: Never, ever use this.)
import Foundation
// Swift's << operator is not left-associative, so we'll use <<< instead
operator infix <<< { associativity left }
// Output operator for Streamable objects
func <<< (var outputStream: OutputStream, streamable: Streamable) -> OutputStream {
// Note: It seems like streamable.writeTo(&outputStream) should work, but playground crashes,
// so we write to a string and then output the string
var outputString = ""
streamable.writeTo(&outputString)
outputStream.write(outputString)
return outputStream
}
// Output operator for Printable objects
func <<< (var outputStream: OutputStream, printable: Printable) -> OutputStream {
outputStream.write(printable.description)
return outputStream
}
// Output operator for functions, e.g. endl()
func <<< (var outputStream:OutputStream, f: OutputStream -> OutputStream) -> OutputStream {
return f(outputStream)
}
// Write newline to a stream
func endl(var outputStream: OutputStream) -> OutputStream {
outputStream.write("\n")
return outputStream
}
// Swift Strings are OutputStreams, so no need for a StringBuilder/StringOutputStream
let myString = ""
myString <<< 1 <<< " + " <<< 2 <<< " = " <<< (1 + 2) <<< endl
print(myString) // "1 + 2 = 3\n"
class ConsoleOutputStream: OutputStream {
func write(string: String) {
print(string)
}
}
let cout = ConsoleOutputStream()
cout <<< "Hello, world!" <<< endl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment