What is the difference between `let` and `var` in Swift? When to use which?
Hello everyone! I just started learning Swift, and I have a fundamental question that seems to haunt all beginners. I can't fully understand the difference between `let` and `var`.
I read that `let` is a constant and `var` is a variable. But in practice, I'm running into confusion. For example, I wrote this code:
```swift
var myName = "Alexey"
myName = "Ivan"
print(myName) // Prints "Ivan" — makes sense, it's a variable
```
But then I tried the same with `let`:
```swift
let myAge = 25
myAge = 30 // Error: Cannot assign to value: 'myAge' is a 'let' constant
```
This is logical — the compiler complains. But then I read that `let` can be undefined until first use. I tried to do this:
```swift
let userName: String
// Some code...
No answers yet.
Log in to leave an answer
Blogs
Functional Programming in Go: Capabilities and Examples
How Rust Turns Bytes into Strings: A Deep Dive Under the Hood
Managing Object Lifetimes in Rust: Secrets of the Garbage Collector
Documentation in Go: Writing Code That Speaks for Itself