Crashalot Crashalot - 2 months ago 287
Swift Question

Swift 3: Cannot convert value of type 'NSMutableDictionary' to expected argument type '[AnyHashable : Any]!'

This code worked before Swift 3. (Curse you Swift 3!)

Now it's showing this error against the

Flurry.logEvent(eventName, withParameters: userData!)
line:


Cannot convert value of type 'NSMutableDictionary' to expected
argument type '[AnyHashable : Any]!'


Casting
userData!
to
[AnyHashable : Any]
produces this error:


Cannot convert value of type 'NSMutableDictionary' to type
'[AnyHashable : Any]' in coercion


func logEvent(_ eventName: String, userData: NSMutableDictionary?) {
// Use <userData> or create new one?
var userData = userData
if userData == nil {
userData = NSMutableDictionary()
}

// Set base properties
userData!.setObject(gUser.tofus.count, forKey: "Num Tofus" as NSCopying)
userData!.setObject(gUser.getLifetimeTofus(), forKey: "Num Lifetime Tofus" as NSCopying)

// Call Flurry
DispatchQueue.main.async {
Flurry.logEvent(eventName, withParameters: userData! as [AnyHashable:Any])
}
}


What's the right syntax for Swift 3?

Answer

If that Flurry.logEvent(_:withParameters:) takes [AnyHashable: Any], why don't you use it as your local userData?

func logEvent(_ eventName: String, userData: NSMutableDictionary?) {
    // Use <userData> or create new one?
    var userData = userData as NSDictionary? as? [AnyHashable: Any] ?? [:]

    // Set base properties
    userData["Num Tofus"] = gUser.tofus.count
    userData["Num Lifetime Tofus"] = gUser.getLifetimeTofus()

    // Call Flurry
    DispatchQueue.main.async {
        Flurry.logEvent(eventName, withParameters: userData)
    }
}
Comments