Kumar Utsav
Kumar Utsav

Reputation: 2841

Non optional expression of type NSDictionary used in a check for optionals. Error

I am getting this alert, while I am trying to load the .plist file. Any suggestion. `

filePath = Bundle.main.path(forResource: Constants.kCPECardHeaderAttribute, ofType: "plist")

And using NSDictionary to load the contents of the file as follows:

guard let fileContentArray:NSDictionary = NSDictionary(contentsOfFile: filePath!)! else{
            return
        }

and I am getting this error. Any help?enter image description here `

Upvotes: 0

Views: 1960

Answers (3)

vadian
vadian

Reputation: 285069

First of all: The variable name fileContentArray and the expected type ...Dictionary is confusing and a contradiction in terms.

You have to pass an optional to use optional bindings, the exclamation mark unwraps the optional which would make the check meaningless. Remove the second !.

However it's highly recommended to use the URL related API and PropertyListSerialiation to get a native Swift collection type:

if let url = Bundle.main.url(forResource:Constants.kCPECardHeaderAttribute, withExtension: "plist") {
    do {
        let data = try Data(contentsOf: url)
        let fileContentDictionary = try PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
        print(fileContentDictionary)

    } catch {
        fatalError("Bad Design! This should never happen").
    }

}

Upvotes: 1

Sulthan
Sulthan

Reputation: 130082

Remove ! after NSDictionary(contentsOfFile:)

guard let fileContentArray = NSDictionary(contentsOfFile: filePath!) else {
    return
}

Both guard-let-else and ! are removing optionals. There is no need to use them both for the same optional.

You could actually use the same pattern for both optionals:

guard
    let filePath = filePath,
    let fileContentArray = NSDictionary(contentsOfFile: filePath)
else {
    return
}

As a side note, it's not common to name variables of dictionary types as arrays.

Upvotes: 6

RJiryes
RJiryes

Reputation: 961

It's because you're using the '!', if you want to check if it's optional you should use ? instead and give it a type that you want.

For Example

guard let fileContentArray:NSDictionary = NSDictionary(contentsOfFile: filePath) ? String else{
        return
    }

Upvotes: -1

Related Questions