Björn Hjorth
Björn Hjorth

Reputation: 2888

Initializer for conditional binding must have Optional type, even if it is a Optional type

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)
}

Upvotes: 0

Views: 126

Answers (2)

NSNoob
NSNoob

Reputation: 5608

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

Upvotes: 3

Shehata Gamal
Shehata Gamal

Reputation: 100503

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 }

Upvotes: 1

Related Questions