0

In Swift 4 I created struct Vybe, an array of Vybe, and a dictionary.

struct Vybe {
        let monthDay: String
        let category: String
        let description: String
    }
var listVybe:[Vybe] = []
var dictVybe = [AnyHashable:Any]()

Then grouped it by a date string.

self.dictVybe = Dictionary(grouping: self.listVybe) { $0.monthDay }

This gave me the structs grouped into an array successfully. But, I am unable to count or iterate through this array. When attempting a for loop I get an error: Type 'Any' does not conform to protocol 'Sequence'. How can I loop or count this group of Array?

Some debugging PRINT:

 print("\(type(of: self.dictVybe["Monday, Jul 16"]!)) ,\(#function)")
 print((self.dictVybe["Monday, Jul 16"]))

OUTPUT:

Array< Vybe> ,fetchData()

Optional([VybrantApp.activityTask.Vybe(monthDay: "Monday, Jul 16", category: "Elated", description: "good desc"), VybrantApp.activityTask.Vybe(monthDay: "Monday, Jul 16", category: "Happy", description: "better desc"), VybrantApp.activityTask.Vybe(monthDay: "Monday, Jul 16", category: "Anxiety", description: "great desc")])

Ryderpro
  • 1,315
  • 10
  • 18

1 Answers1

0
( dictVybe[ "Monday, Jul 16" ] as! [ Vybe ] ).count

does the thing.

Satachito
  • 5,838
  • 36
  • 43
  • What does `as! [ Vybe ]` do here? Set it to an array of struct? – Ryderpro Jul 17 '18 at 03:32
  • dictVybe's value is type of [ Vibe ] because you have created by Dictionary(grouping: self.listVybe) { $0.monthDay }, so you can cast the value to the type of [ Vibe ] which is countable and iteratable. Refer https://stackoverflow.com/questions/29637974/whats-the-difference-between-as-as-and-as – Satachito Jul 17 '18 at 03:39