Skip to content

Instantly share code, notes, and snippets.

@kurko
Last active December 14, 2015 13:59
Show Gist options
  • Save kurko/ac90d3134bf183b94eb2 to your computer and use it in GitHub Desktop.
Save kurko/ac90d3134bf183b94eb2 to your computer and use it in GitHub Desktop.
Swift: confusion optionals
var myDictionary: [String: String] = [:] // Same behavior with `String!`
myDictionary["My key"] = "My non-optional string" // This is a normal string
// It would be fine if it was wrapped in an optional just for print()
print("My output: \(myDictionary["My key"])") // outputs 'My output: Optional("My non-optional string")")'
// However, it's wrapped by default and that has serious implications
// in the source code. I spent hours debugging a problem last weekend
// just to find out that a mere string had become an Optional.
//
// In the following, I don't understand the reasoning for it to fail
// until I checked that `if` myself and found out that it was an Optional:
print(myDictionary["My Key"] == "My non-optional String") // returns false
@carlosgaldino
Copy link

// In a language without the Option type like Ruby:
hash = {}
hash["My key"] = "My value"
hash["My key"] // => "My value"
hash["My wrong key"] // => nil

// In a language with the Option type like Rust, Haskell, Swift, etc:
let mut hash = HashMap::new();
hash.insert("My key", "My value");
hash.get("My key"); // => Some("My value")
hash.get("My wrong key"); // => None

// What would be the returned value for a key that doesn't exist? You don't have `nil` in such languages...
// The key might or might not be present in the hash so the hash needs to return an Option type to reflect the presence or absence of a value for such key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment