UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

2      

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?

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.