Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

ios - Swift 2.0 Sorting Array of Objects by Property

In Swift 2.0, how would you go about sorting an array of custom objects by a property? I know in Swift 1.2, this was done using sorted() and sort(). However, these methods no longer work in Xcode 7 beta 4. Thanks!

For example:

class MyObject: NSObject {
    var myDate : NSDate
}

...

let myObject1 : MyObject = MyObject() //same thing for myObject2, myObject3

var myArray : [MyObject] = [myObject1, myObject2, myObject3] 

//now, I want to sort myArray by the myDate property of MyObject.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Swift 2:

  • You can use sort method, using compare to compare the two dates:

    let sortedArray = myArray.sort { $0.myDate.compare($1.myDate) == .OrderedAscending }  // use `sorted` in Swift 1.2
    
  • Or, if you want to sort the original array, you can sortInPlace:

    myArray.sortInPlace { $0.myDate.compare($1.myDate) == .OrderedAscending }  // use `sort` in Swift 1.2
    

In Swift 3:

  • to return a sorted rendition of the array, use sorted, not sort

    let sortedArray = myArray.sorted { $0.myDate < $1.myDate }
    
  • to sort in place, it's now just sort:

    myArray.sort { $0.myDate < $1.myDate }
    

And with Swift 3's Date type, you can use the < operator.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...