Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Last active September 14, 2015 20:48
Show Gist options
  • Save wjlafrance/8334888cd83c306fed8c to your computer and use it in GitHub Desktop.
Save wjlafrance/8334888cd83c306fed8c to your computer and use it in GitHub Desktop.
MethodsOfHandlingNil.swift
/**
* The contract of this method is that the method will check if unsafeThing is nil before using it.
* This contract is not encoded in the method signature and is not compiler-enforced!
*/
func safelyHandlesIUO(unsafeThing: String!) {
println("This isn't an optional. We can use it directly but may find nil and crash: \(unsafeThing)")
if let safeThing = unsafeThing {
println("String is \(count(safeThing)) length")
} else {
println("Woah, we would have crashed if we passed it to count!")
// println("String is \(count(unsafeThing)) length") // uncomment this for crash
}
}
/**
* The contract of this method is that the programmer promises unsafeThing will never be nil.
* Violation of this contract will cause a crash.
* This contract is not encoded in the method signature and is not compiler-enforced!
*/
func assertivelyHandleIUO(unsafeThing: String!) {
precondition(nil != unsafeThing, "Our caller promises the argument is non-nil!")
println("String is \(count(unsafeThing)) length")
}
/**
* The contract of this method is that the method will check if maybeThing is nil before using it.
* This contract IS encoded in the method signature and IS compiler enforced.
* Do this!
*/
func handleOptional(maybeThing: String?) {
if let safeThing = maybeThing {
println("String is \(count(safeThing)) length")
} else {
println("The compiler wouldn't let us do anything unsafe, as long as method contracts are in their signatures.")
// println("String is \(count(safeThing)) length") // uncomment this for compiler error
}
}
safelyHandlesIUO("This is safe.")
safelyHandlesIUO(nil)
assertivelyHandleIUO("This is safe.")
//assertivelyHandleIUO(nil) // uncomment this to crash
handleOptional("This is safe.")
handleOptional(nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment