Working with optionals in swift?

Example:


  var name: String?
  print(name)
  

In Swift, variables can be declared as 'Optionals', which means they can hold a value or be nil. The above code will print 'nil'.

Solution:


  var name: String? = "ChatGPT"
  if let unwrappedName = name {
      print(unwrappedName)
  }
  

By using 'if let', you can unwrap the optional value safely and use it.

Beginner's Guide to Swift