Avatar ·

What is null/nil in Swift and how to work with it?

Hello everyone! I'm learning Swift and came across the concept of null/nil. In other languages (e.g., Java, C#) I'm used to null references and NullPointerException. But in Swift, as I understand, nil is not a pointer, but the absence of a value for optional types (Optional).

I have a simple example: I'm trying to get a username from a dictionary, but if the key doesn't exist, the app crashes.

let user: [String: Any] = ["name": "Alice"]\nlet name = user["age"] as! String // crash if key doesn't exist\nprint(name)

I've tried using if let and guard let, but I don't fully understand how to properly handle nil in different situations. For example:

  • What is the difference between Optional and forced unwrapping?
  • When to use ?? (nil-coalescing) instead of if let?
  • Can a regular