Khalil Rumman
Khalil Rumman

Reputation: 557

Swift Custom NSMutableArray Sorting

I have a custom NSMutableArray and i want to sort it; I've looked over the internet but nothing solve my problem. what I have is the following Locations.swift

import UIKit

class Location: NSObject {
    var id:String = String()
    var name:String = String()
    var distance:Float = Float()
}

then I create a Mutable Array from this class in my ViewController.swift

class CustomViewController: UIViewController{
    var locations: NSMutableArray!

    override func viewDidLoad() {
        super.viewDidLoad()
        locations = NSMutableArray()
        locations = SqLite.getInstnace().getLocations()//get values from DB، objects of Location
    }

}

how I can sort locations by the distance value??

Upvotes: 2

Views: 1772

Answers (2)

boidkan
boidkan

Reputation: 4731

You could always use the built in sort function:

    let locations = SqLite.getInstnace().getLocations().sort({
        return ($0 as! Location).distance < ($1 as! Location).distance
    })

if SqLite.getInstnace().getLocations() return an array as [Location] and not a NSArray then you could just do this since it will already know the elements types:

    let locations = SqLite.getInstnace().getLocations().sort({
        return $0.distance < $1.distance
    })

This should return a sorted array in ascending order if you want descending just use > instead.

Also, there is really no need to use NSMutableArrays in Swift. Just use [Location].

Edit:

NSMutableArray can be used in swift but it considered objective-c like where as using [OBJECT_TYPE] is conventional for swift.

Take a look at the Swift 2 book array segment. None of the examples use NSArray or NSMutable array.

By declaring something with var in swift makes it mutable where as let makes something immutable

Upvotes: 3

Aaron Rasmussen
Aaron Rasmussen

Reputation: 13316

I would make location an array of Location objects, and then sorting becomes easy with sortInPlace.

class CustomViewController: UIViewController{
    var locations = [Location]()

    override func viewDidLoad() {
        super.viewDidLoad()
        locations = SqLite.getInstnace().getLocations().flatMap { $0 as? Location }
    }
}

Now you can sort locations like this:

locations.sortInPlace { $0.distance < $1.distance }

Upvotes: 3

Related Questions