Skip to content

Instantly share code, notes, and snippets.

@Gurpartap
Last active October 5, 2016 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gurpartap/bc72e18335fb037fcce1417793b9211e to your computer and use it in GitHub Desktop.
Save Gurpartap/bc72e18335fb037fcce1417793b9211e to your computer and use it in GitHub Desktop.
swift optionals in go? tcard/sgo#27
// 1. Like SGo
var regularVar: String
// This will _not compile_.
// print(regularVar)
// This will _not compile_.
// regularVar = nil
regularVar = "value"
print(regularVar) // "value"
print(type(of: regularVar)) // "String"
// 2. Like SGo with ?
var optionalWrappedVar: String?
print(optionalWrappedVar) // "nil"
print(type(of: optionalWrappedVar)) // "Optional<String>"
// This will crash during runtime.
// print(optionalVar!)
optionalWrappedVar = nil
optionalWrappedVar = "value"
print(optionalWrappedVar) // "Optional("value")"
// Now that it has a value, it will not crash when unwrapped.
print(optionalWrappedVar!) // "value"
print(type(of: optionalWrappedVar!)) // "String"
// But the use of ! remains crash prone, so unwrap with an expression.
if let unwrappedVar = optionalWrappedVar {
print(unwrappedVar) // "value"
print(type(of: unwrappedVar)) // "String"
} else {
// nil.
}
// 3. Like Go (or perhaps SGo with !)
var implictlyUnwrapperOptionalVar: String!
// This will crash during runtime.
// print(implictlyUnwrapperOptional)
implictlyUnwrapperOptionalVar = nil
implictlyUnwrapperOptionalVar = "value"
print(implictlyUnwrapperOptionalVar) // "value"
print(type(of: implictlyUnwrapperOptionalVar)) // "ImplicitlyUnwrappedOptional<String>"
if let unwrappedVar = implictlyUnwrapperOptionalVar {
print(unwrappedVar) // "value"
print(type(of: unwrappedVar)) // "String"
} else {
// nil.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment