Avatar ·

What does the exclamation mark mean in Swift? Problem with optional types

Hello everyone! I just started learning Swift, and I'm confused about the exclamation mark. I've seen that `!` is often used after variables in code, but I don't fully understand why it's needed.\n\nHere's an example I found in a textbook:\n\n```swift\nvar optionalString: String? = "Hello"\nprint(optionalString!) // Prints "Hello"\n```\n\nIf I remove the exclamation mark, the compiler gives a warning that `optionalString` needs to be unwrapped. But why? The variable clearly contains a string. I tried writing my own code:\n\n```swift\nvar name: String? = "John"\nlet greeting = "Hello, " + name // Error: Value of optional type 'String?' must be unwrapped\n```\n\nWhy doesn't Swift allow just using the value? And what happens if I apply `!` to `nil`? I've heard that this is a