简体   繁体   中英

Swift: Sort Array in Alphabetical Order

I'm very new at Swift and Objective-C.

I have a table view controller in which I have declared a dictionary and an array:

var parts = [:]
var partsSectionTitles: NSArray!

In my viewDidLoad function, I have:

parts = [
        "Part 1" : ["X:1", "X:2", "X:3"],
        "Part 2" : ["X:1", "X:2"],
        "Part 3" : ["X:1"]
    ]

var partsSectionTitles = parts.allKeys

I've already successfully completed this table view controller in Objective-C, and in order to sort the partsSectionTitles alphabetically, I used:

partsSectionTitles = [[parts allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

So, my question is: How do I write the preceding Objective-C code in Swift? Thank you in advance for your answers.

UPDATE: I was able to solve the problem using bits and pieces from the answers you guys provided. So, thank you! Here's what I have:

I declared the parts dictionary as:

var parts = [String:[String]]()

which allowed me to provide multiple values to each key. This was a HUGE help.

Then I was able to create the partsSectionTitles and sort it:

partsSectionTitles = [String](parts.keys)
partsSectionTitles.sort(){ $0 < $1 }

This worked as I received no errors.

This should meet your need. The array contains String element.

var partsSectionTitles:[String] = partsOfNovel.allKeys as [String]
var sortedNames = partsSectionTitles.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedDescending }

What about a nice Quicksort function to order your array of Strings? ( Source )

First create an Array extension to decompose the given array:

extension Array {
  var decompose : (head: T, tail: [T])? {
    return (count > 0) ? (self[0], Array(self[1..<count])) : nil
  }
}

Second create the Quicksort function so you can order the decomposed Array:

func qsort(input: [String]) -> [String] {
  if let (pivot, rest) = input.decompose {
    let lesser = rest.filter { $0 < pivot }
    let greater = rest.filter { $0 >= pivot }
    return qsort(lesser) + [pivot] + qsort(greater)
  } else {
    return []
  }
}

Declare the variables with explicit type (Dictionary and Array):

var partsOfNovel = [​String​ : [String]]()
var partsSectionTitles = [String]()

Fill them:

partsOfNovel = [
  "Part 1" : ["Chapter X:1", "Chapter X:2", "Chapter X:3"],
  "Part 2" : ["Chapter X:1", "Chapter X:2"],
  "Part 3" : ["Chapter X:1"]
]

partsSectionTitles = partsOfNovel.allKeys
// ["Part 1", "Part 3", "Part 2"]

And finally order your Strings Array:

var orderedSectionTitles = qsort(partsSectionTitles)
// ["Part 1", "Part 2", "Part 3"]

I think is a nice solution in pure Swift , I hope it helps!

let array = ["j","d","k","h","m"]
func backward(x : String, y: String) -> Bool
{
    return x>y
}

var reverse = sorted(array,backward)


println((reverse))

or you can write like :

var newrev = sorted(array, {$0 < $1})

or

var other = sorted (array , >)

Let's say you have the following Objective-C code with NSDictionary and NSArray :

NSDictionary *partsOfNovel = @{@"Part 1" : @[@"Chapter X:1", @"Chapter X:2", @"Chapter X:3"],
                               @"Part 4" : @[@"Chapter X:1", @"Chapter X:2"],
                               @"Part 3" : @[@"Chapter X:1"]};

NSArray *partsSectionTitles = [[partsOfNovel allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSLog(@"%@", partsSectionTitles);

With this code, your console will print:

"Part 1",
"Part 3",
"Part 4"

With Swift, you can get the keys of a Dictionary and put them in a Array like this:

let partsOfNovel = [
    "Part 1" : ["Chapter X:1", "Chapter X:2", "Chapter X:3"],
    "Part 4" : ["Chapter X:1", "Chapter X:2"],
    "Part 3" : ["Chapter X:1"]]

let nonOrderedPartsSectionTitles = partsOfNovel.keys.array

You can then apply a sort on this Array and print the result like this:

let partsSectionTitles = nonOrderedPartsSectionTitles.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
println(partsSectionTitles) //[Part 1, Part 3, Part 4]

But all of this can be done with Swift in a much concise way (tested with Playground):

let partsOfNovel = [
    "Part 1" : ["Chapter X:1", "Chapter X:2", "Chapter X:3"],
    "Part 4" : ["Chapter X:1", "Chapter X:2"],
    "Part 3" : ["Chapter X:1"]]

let partsSectionTitles = partsOfNovel.keys.array.sorted { $0.0 < $1.0 }
println(partsSectionTitles) //[Part 1, Part 3, Part 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM