0

I have two class and I added both class object in same array and both class object have property date and below is my code:

protocol MyType {

}


class A: MyType {

    var type: Int?
    var date: String?

    init(type: Int, date: String) {
        self.type = type
        self.date = date
    }
}

class B: MyType {

    var name: String?
    var date: String?

    init(name:String, date: String) {
        self.name = name
        self.date = date
    }
}

var array = [MyType]()

let AObject1 = A(type: 1, date: "2015-11-04")
let AObject2 = A(type: 2, date: "2015-11-05")
let BObject1 = B(name: "Birthday", date: "2015-11-03")
let BObject2 = B(name: "Events", date: "2015-11-12")

array.append(AObject1)
array.append(AObject2)
array.append(BObject1)
array.append(BObject2)

All object are added into array successfully but I have no I idea how can I short it with date property.

Any help would be appreciate.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
  • see this [link1](http://stackoverflow.com/questions/31729337/swift-2-0-sorting-array-of-objects-by-property) & [link2](http://stackoverflow.com/questions/33357568/swift-2-sort-multi-dimensional-array-by-date) , if you not get the idea reply here we will support you – Anbu.Karthik Nov 07 '15 at 06:22
  • final array you can sort with date using `array.sort { $0.yourdate < $1.yourdate }` else in place you can sort `array.sortInPlace { $0.yourdate < $1.yourdate }`, dont bothering in instance array – Anbu.Karthik Nov 07 '15 at 06:27

1 Answers1

1

Add the date property to your protocol:

protocol MyType {
    var date: String? { get }
}

Then you can sort the array with something similar to:

array.sort { $0.date < $1.date }

or sort it in place with

array.sortInPlace { $0.date < $1.date }

Note that the string format your using allows you to use lexicographic sorts to achieve date sorted order, otherwise you might want to store the dates as NSDates.

David Berry
  • 40,941
  • 12
  • 84
  • 95