Difference Between Sort and Sortinplace in Swift 2

sorted function in Swift 2

Follow what the error message is telling you, and call sort on the collection:

users.sort(back)

Note that in Swift 2, sorted is now sort and the old sort is now sortInPlace, and both are to be called on the array itself (they were previously global functions).

Be careful, this has changed again in Swift 3, where sort is the mutating method, and sorted is the one returning a new array.

Swift 2.0 Sorting Array of Objects by Property

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.

Swift - Sort array of objects with multiple criteria

Think of what "sorting by multiple criteria" means. It means that two objects are first compared by one criteria. Then, if those criteria are the same, ties will be broken by the next criteria, and so on until you get the desired ordering.

let sortedContacts = contacts.sort {
if $0.lastName != $1.lastName { // first, compare by last names
return $0.lastName < $1.lastName
}
/* last names are the same, break ties by foo
else if $0.foo != $1.foo {
return $0.foo < $1.foo
}
... repeat for all other fields in the sorting
*/
else { // All other fields are tied, break ties by last name
return $0.firstName < $1.firstName
}
}

What you're seeing here is the Sequence.sorted(by:) method, which consults the provided closure to determine how elements compare.

If your sorting will be used in many places, it may be better to make your type conform to the Comparable protocol. That way, you can use Sequence.sorted() method, which consults your implementation of the Comparable.<(_:_:) operator to determine how elements compare. This way, you can sort any Sequence of Contacts without ever having to duplicate the sorting code.

Swift sort array by 2 parameters

Okay, if you want to sort by company first and then by name, you first have to check for equality of the companies. If the companies are the same, you fall back to sorting by name, otherwise, you just return the result of the comparison between the two companies.

self.storage.sortInPlace {
if ($0["company"] as! String) == ($1["company"] as! String)
{
return ($0["name"] as! String) < ($1["name"] as! String)
}
return $0["company"] as! String) < ($1["company"] as! String)
}

or even shorter:

self.storage.sortInPlace { (($0["company"] as! String) == ($1["company"] as! String)) ? (($0["name"] as! String) < ($1["name"] as! String)) : ($0["company"] as! String) < ($1["company"] as! String)) }

Swift 2.1 Error sorting in place, only on release builds

This code looks correct. It sounds like you've run across a bug in the compiler, which is generally the case when you have a crash in release configuration but not debug. You can perhaps verify this by enabling optimizations in your debug build and testing to see if it generates the problem. Aside from your workaround, the only other thing you need to do is file a bug.

Sort array by second letter in swift 2.2

As an alternative to using subStringFromIndex—an alternative suitable specifically for the case of sorting by the second character (and in case of equality; following characters lexicographically) of each string—you can use the dropFirst() method of the CharacterView of each string:

let strings = ["hello", "bye", "how", "etc"]
let sortedStrings = strings
.sort { String($0.characters.dropFirst()) < String($1.characters.dropFirst()) }

print(sortedStrings) // ["hello", "how", "etc", "bye"]

This is equivalent to the solution using substringFromIndex and advancedBy, with the upside that this will not yield a runtime exception in case the strings array contain an empty string ("") (although this can be remedied for the advancedBy solution by using .advancedBy(1, limit: $0.endIndex) and .advancedBy(1, limit: $1.endIndex) for the sorting keys, respectively).


Note also that lexicographical comparison will sort uppercase letters prior to any lowercase letter, such that ["hello", "bYe", "hOw", "etc"] will sort into ["hOw", "bYe", "hello", "etc"]. If you want case-insensitive sorting, you can apply the .lowercaseString property to the sorting keys:

let strings = ["hello", "bYe", "hOw", "etc"]
let sortedStrings = strings
.sort { String($0.lowercaseString.characters.dropFirst()) <
String($1.lowercaseString.characters.dropFirst()) }

print(sortedStrings) // ["hello", "hOw", "etc", "bYe"]

Swift 2.0: Type of Expression is ambiguous without more context? SortInPlace

NSURL's absoluteString is non-optional and you're force unwrapping it.

Rewrite the sort as follows

    images.sortInPlace( { $0.URL.absoluteString > $1.URL.absoluteString } )

How to sort an array of custom objects by property value in Swift

First, declare your Array as a typed array so that you can call methods when you iterate:

var images : [imageFile] = []

Then you can simply do:

Swift 2

images.sorted({ $0.fileID > $1.fileID })

Swift 3

images.sorted(by: { $0.fileID > $1.fileID })

Swift 5

images.sorted { $0.fileId > $1.fileID }

The example above gives the results in descending order.

Sorting NSMutableArray depending on priority

Try this:

let result = arr.sort {
let p0 = $0["points"] as! Int
let p1 = $1["points"] as! Int

let lp0 = $0["lastPoints"] as! Int
let lp1 = $1["lastPoints"] as! Int

let online0 = $0["online"] as! NSDate
let online1 = $1["online"] as! NSDate

if p0 != p1 {
return p0 > p1
} else if lp0 != lp1 {
return lp0 > lp1
} else {
return online0.timeIntervalSince1970 > online1.timeIntervalSince1970
}
}


Related Topics



Leave a reply



Submit