WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

How do I create a new Dictionary extension that returns a specific type of dictionary

Forums > Swift

@Apps  

Sorry if this is a stupid question.

I need to create a Dictionary class or extension that returns a dictionary of type [String, AnyObject]

I did this

extension Dictionary {

  static func createDict(screenOn: Bool,
                               delay: String,
                               duration: Float) -> Dictionary<String,AnyObject> {

    return ["screenOn": screenOn,
       "delay": delay,
       "duration": duration]
  } 
}

I have these errors:

Cannot convert value of type 'Bool' to expected dictionary value type 'AnyObject'

Cannot convert value of type 'String' to expected dictionary value type 'AnyObject'

Cannot convert value of type 'Float' to expected dictionary value type 'AnyObject'

how do I solve that?

   

AnyObject refers to classes; Bool, String and Float are not classes in Swift.

You need to use Any if you are putting Bool, String and Float values in your Dictionary.

Paul has an article about the difference: What’s the difference between Any and AnyObject?

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.