Last active
August 29, 2015 14:02
-
-
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.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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