Skip to content

Instantly share code, notes, and snippets.

@radex
Created August 28, 2014 09:40
Show Gist options
  • Save radex/3733d696450db118a1e5 to your computer and use it in GitHub Desktop.
Save radex/3733d696450db118a1e5 to your computer and use it in GitHub Desktop.
Swift allows you to declare a (non-optional) variable in a local scope without setting its value if the compiler can deduce that the value _will_ be set before it's used.
// This will work:
var url: String
if condition {
url = "http://example.com"
} else {
url = "http://example.org"
}
doSomethingWithUrl(NSURL(string: url))
// If you tried to use `url` before its value was set, or
// _any_ of the branches didn't initialize it (e.g. if you omitted `else`),
// it would fail in compile time.
// Well done, Swift compiler.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment