按日期排序多个继承对象的数组

时间:2015-09-27 12:16:50

标签: ios arrays swift sorting

我有一个数组array: [AnyObject],其中包含许多不同的继承对象,例如DogCat。我想按日期排序,我该怎么做?

这些类可以看起来像这样

class Pet {
    var: NSDate = NSDate()
}

class Dog: Pet {
}

class Cat: Pet {
}

到目前为止,我已经创建了这个类,它假设处理排序并返回一个新对象排序的数组

class FavoriteSorter {
    func sortOrganizationsByDistanceFromLocation(orgArray:[AnyObject]) -> [AnyObject] {


        let sortedArray = orgArray.sort {

        }



        return sortedArray

    }
}

2 个答案:

答案 0 :(得分:0)

class FavoriteSorter {
    func sortOrganizationsByDistanceFromLocation(array:[AnyObject]) -> [AnyObject] {
        return array.sort{ ($0.0 as! Pet).date.compare(($0.1 as! Pet).date) == NSComparisonResult.OrderedAscending }
    }
}

正如vacawama所提到的,最好传递[Pet]而不是[AnyObject],以避免在你传递另一个对象类型时崩溃:

class FavoriteSorter {
    func sortOrganizationsByDistanceFromLocation(array:[Pet]) -> [Pet] {
        return array.sort{ $0.date.compare($1.date) == NSComparisonResult.OrderedDescending }
    }
}

class Pet {
    var date = NSDate()
}
class Dog: Pet { }
class Cat: Pet { }

let dog = Dog()
let cat = Cat()

let date01 = NSDate()
let date02 = NSDate().dateByAddingTimeInterval(3600)

dog.date = date01
cat.date = date02

let pets = [dog,cat]
pets.description   // "[Dog, Cat]"

let sortedPets = FavoriteSorter().sortOrganizationsByDistanceFromLocation(pets)
sortedPets.description   //  "[Cat, Dog]"

答案 1 :(得分:0)

试试这个:

class Pet {
    var myDate = NSDate()
    var title = String()
}

class Dog: Pet {
}

class Cat: Pet {
}


var dog1 = Dog()
dog1.myDate = NSDate()
dog1.title = "Dog 1"

var dog2 = Dog()
dog2.myDate = NSDate(timeIntervalSinceNow:NSTimeInterval(10))
dog2.title = "Dog 2"

var cat1 = Cat()
cat1.myDate = NSDate(timeIntervalSinceNow:NSTimeInterval(20))
cat1.title = "Cat 1"

var cat2 = Cat()
cat2.myDate = NSDate(timeIntervalSinceNow:NSTimeInterval(15))
cat2.title = "Cat 2"

var arrayOfObjs = [cat1, cat2, dog1, dog2]

// Sorting array
func sortOrganizationsByDistanceFromLocation(array:[AnyObject]) -> [AnyObject] {
    return array.sort{ ($0.0 as! Pet).myDate.compare(($0.1 as! Pet).myDate) == NSComparisonResult.OrderedAscending }
}

let sortedArray = sortOrganizationsByDistanceFromLocation(arrayOfObjs) as! [Pet]

print(sortedArray[0].title); // Prints Dog 1
print(sortedArray[1].title); // Prints Dog 2
print(sortedArray[2].title); // Prints Cat 2
print(sortedArray[3].title); // Prints Cat 1