Last active
October 5, 2016 09:29
-
-
Save Gurpartap/bc72e18335fb037fcce1417793b9211e to your computer and use it in GitHub Desktop.
swift optionals in go? tcard/sgo#27
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
// 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" |
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
// 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. | |
} |
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
// 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