Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Created April 1, 2015 16:08
Show Gist options
  • Save wjlafrance/d85503795476b2116c2b to your computer and use it in GitHub Desktop.
Save wjlafrance/d85503795476b2116c2b to your computer and use it in GitHub Desktop.
Void is a type!
// This playground was built for Xcode 6.2 and is compatible with Xcode 6.3b3.
// The contents are true to the best of my knowledge and are not an April Fools joke.
// However, if you -actually- implement some of this stuff...
// In Swift, Void is a typealias for an empty tuple
// Cmd-Click the keyword Void to see this typealias
func example1() {
let myVoid: Void = ()
println("\(myVoid)")
}
example1()
// Remember, a tuple can be decomposed
// See 'The Swift Programming Language', pg 55
func example2() {
let myTuple = ("hello", "world")
let (word1, word2) = myTuple
println("\(word1), \(word2)")
}
example2()
// You can also decompose the results of a tuple-returning function call directly
func example3() {
func returnsTuple() -> (String, String) {
return ("hello", "world")
}
let (word1, word2) = returnsTuple()
println("\(word1), \(word2)")
}
example3()
// Since Void is a type, you can assign the results of a Void-returning function call
func example4() {
func returnVoid() -> Void {}
let myVoid: Void = returnVoid()
println("\(myVoid)")
}
example4()
// Keep in mind that since the return type of a function is implicitly Void, you can assign a function call even without
// an explicit return type
func example5() {
func returnVoid() {}
let () = returnVoid()
}
example5()
// You can also use tuple-decomposition syntax, assigning it to an 0-length list of variables
func example6() {
func returnVoid() {}
let () = returnVoid()
}
example6()
// This explains all kinds of errors you see regarding type '()' when you're not dealing with tuples
// Uncomment the following function to see some of these errors
//func example7() {
// func attemptToReturnNonZeroLengthTuple() {
// // error: type '()' does not conform to protocol 'IntegerLiteralConvertible'
// return (1)
// }
// func attemptToReturnConcreteObject() {
// // error: 'String' is not convertible to '()'
// return "hello world"
// }
//}
//example7()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment