Contextual type 'AnyObject' cannot be used within dictionary literal

Please help, I am trying to follow the video tutorial here: https://www.youtube.com/watch?v=D0MuaFzoxng (TIme: 34:32)



I get the following error, please help

Contextual type 'AnyObject' cannot be used within dictionary literal


here is my code:

func toAnyObject() -> AnyObject {
        return ["content":content, "addedByUser":addedByUser]
    }

Replies

The problem you’re having here is that Swift’s

Dictionary
type is a struct, not an object, so you can’t use it as the return value of a function that returns
AnyObject
. You can either return an NSDictionary, which is an object:
func toAnyObject() -> AnyObject { 
    return ["content":content, "addedByUser":addedByUser] as NSDictionary
}

or change the return type to `Any:

func toAnyObject() -> Any { 
    return ["content":content, "addedByUser":addedByUser]
}

It’s hard to say what the right option is without knowing more about the context.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"