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.

2
  • see this link1 & link2 , if you not get the idea reply here we will support you Commented Nov 7, 2015 at 6: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 Commented Nov 7, 2015 at 6:27

1 Answer 1

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.

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

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.