0

I got an error I do not understand, as I thought I understood unwrapping a conditional var/let. But when I try to force unwrap it in the if I get the supplied error.

Error:

Initializer for conditional binding must have Optional type, not 'String'  

Code:

let imNotSet: String?

print(type(of: imNotSet)) // Optional<String>

if let unwrappedVar = imNotSet! { // error on this line
    print(unwrappedVar)
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
Björn Hjorth
  • 2,459
  • 5
  • 25
  • 31

2 Answers2

3
if let unwrappedVar = imNotSet! { // error on this line
    print(unwrappedVar)
}

imNotSet! forcefully unwrapped imNotSet. So it is no longer an optional but rather a string.

To keep it an optional, remove the forced unwrapping.

if let unwrappedVar = imNotSet { // error fixed
        print(unwrappedVar)
    }

if let allows you to safely unwrap the optional, unlike the forced unwrapping that you were doing before.

As for Constant 'imNotSet' used before being initialized error, Either provide it a value like let imNotSet: String? = "Sample", if it truly is a constant, before you use it. Or make it a var if you need to reset it later like var imNotSet: String? = nil

NSNoob
  • 5,548
  • 6
  • 41
  • 54
  • So how does that work when I am using the `imNotSet` as a const? as now I get the error `Constant 'imNotSet' used before being initialized` – Björn Hjorth Feb 11 '19 at 09:43
  • @BjörnHjorth Either provide it a value`let imNotSet: String? = "Sample"` if it truly is a constant before you use it, or make it a var if you need to reset it later `var imNotSet: String? = nil`. – NSNoob Feb 11 '19 at 09:45
  • So it's not possible to make a check for this situation: it's either nil or a constant value? – Björn Hjorth Feb 11 '19 at 09:46
  • 1
    Pretty much. Optional Constants don't automatically default to nil as Martin said. Since you presumably need to change the value, you should use var anyways instead of let – NSNoob Feb 11 '19 at 09:49
1

the var to be used with if let it must be an optional and this

imNotSet!

isn't , so replace

if let unwrappedVar = imNotSet! {

with

guard let unwrappedVar = imNotSet else { return }
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87