0

I'm trying to take an array or JSON data and group the values in the array by date using the following code:

func groupTrips (trips: JSON) -> [[Trip?]] {
    let calendar = NSCalendar.currentCalendar()
    var groupedTrips:[[Trip?]] = []
    var group: [Trip] = []
    for (index, tripRaw):(String, JSON) in trips {
      let trip = Trip(trip: tripRaw)
      if index == "0" && calendar.compareDate(trip.pickup, toDate: NSDate.init(), toUnitGranularity: .Day) != .OrderedSame {
        groupedTrips.append([nil])
      }
      if let lastTrip = group.last {
        let order = calendar.compareDate(trip.pickup, toDate: lastTrip.pickup, toUnitGranularity: .Day)
        if order == .OrderedSame {
          group.append(trip)
        } else {
          groupedTrips.append(group)
          group = [trip]
        }
      } else {
        group.append(trip)
      }
    }
    groupedTrips.append(group)
    return groupedTrips
  }

When I try to run the code, I get an error on the 3rd to last line groupedTrips.append(group): Thead 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) And in my console, I get fatal error: array cannot be bridged from Objective-C. My Trip class is just a simple Swift class that parsed the JSON element into objects.

2
  • I don't really know if it's the best way to fix the issue but generally I change the class to a struct. Works unless you extend/implement something and if you don't mind that it's value type rather than a reference type. I believe that you can also generally fix it extending NSObject, but not so sure on that one. Commented Mar 21, 2016 at 15:00
  • @TedHuinink: It looks like changing to a struct worked. Probably a good idea if I want to use the simplest object type possible to contain values. Turn your comment into an answer and I'll mark it correct. Commented Mar 21, 2016 at 15:38

2 Answers 2

1

I don't really know if it's the best way to fix the issue but generally I change the class to a struct. Works unless you extend/implement something and if you don't mind that it's value type rather than a reference type.

Sign up to request clarification or add additional context in comments.

Comments

1

You should look at Comparable. Implementing this in your Trip reference would allow you to use the sort() function. Apart from that, I would recommend digesting Swift's functional aspects. I think your code could be cleaned up and simplified significantly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.