Non-optional expression of type 'AnyObject' used in a check for optionals
Asked Answered
H

2

9

I created an extension on 'Dictionary' to help me parse JSON. The method below helps me do this:

func toJSONString() -> String? {
    if let dict = self as? AnyObject {
        if let data = try? JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions(rawValue: 0)) {
            if let json = String(data: data, encoding: String.Encoding.utf8) {
                return json
            }
        }
    }
    return nil
}

The issue occurs on this line:

if let dict = self as? AnyObject {

I get a warning saying "Non-optional expression of type 'AnyObject' used in a check for optionals"

How do I go about solving this issue?

Hengel answered 30/9, 2016 at 20:18 Comment(4)
You don't need to unwrap or cast self, you already know it's a dictionary. Just pass self directly to the JSONSerialization.data(...) function.Kelda
The error message says: The object is not an optional, if let can not be used.Latoshalatouche
Ahhh that makes sense. Thank you so muchHengel
Could you answer your own question please, interested to see the solution.Munguia
Y
2

Simply remove the line that causes warning from your code and pass self as is for the JSONSerialization function. This should work without any issues:

extension Dictionary {

    func toJSONString() -> String? {
        if let data = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0)) {
            if let json = String(data: data, encoding: String.Encoding.utf8) {
                return json
            }
        }

        return nil
    }
}
Yee answered 6/4, 2017 at 13:53 Comment(0)
D
1

Your are unwrapping something that was already unwrapped. Take a look at this stackoverflow post

Dewain answered 17/1, 2017 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.