Actually when you define any variable as a optional then you need to unwrap that optional value. To fix this problem either you have to declare variable as non option or put !(exclamation) mark behind the variable to unwrap the option value.
var optionalVariable : String? // This is an optional.
optionalVariable = "I am a programer"
print(optionalVariable) // Optional("I am a programer")
var nonOptionalVariable : String // This is not optional.
nonOptionalVariable = "I am a programer"
print(nonOptionalVariable) // "I am a programer"
//There are different ways to unwrap optional varialble
// 1 (Using if let or if var)
if let optionalVariable1 = optionalVariable {
print(optionalVariable1)
}
// 2 (Using guard let or guard var)
guard let optionalVariable2 = optionalVariable else {
fatalError()
}
print(optionalVariable2)
// 3 (Using default value ?? )
print(optionalVariable ?? "default value") // If variable is empty it will return default value
// 4 (Using force caste !)
print(optionalVariable!) // This is unsafe way and may lead to crash