tedArrayUsingComparator对NSArray进

tedArrayUsingComparator对NSArray进

本文介绍了使用sortedArrayUsingComparator对NSArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C中,我可以使用以下语句对NSArray进行排序:

In Objective-C I can sort an NSArray using this statement:

NSArray *sortedArray = [persons sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2) {
    return [p1.name compare:p2.name];
}];

我无法使用 Swift 重现相同的声明.我发现的只是使用Array.

I'm unable to reproduce the same statement with Swift. All I found was using Array.

推荐答案

您可以使用,或者,由于Swift数组已桥接到NSArray,因此您可以直接从swift调用sortedArrayUsingComparator.

You can either use Swift's built in sort functions or, since a Swift array is bridged to NSArray you can call sortedArrayUsingComparator from swift directly.

使用Swift的sorted函数:

Using Swift's sorted function:

var sortedArray = sorted(persons) {
    (obj1, obj2) in

    // The downcast to Person is only needed if persons is an NSArray or a Swift Array of AnyObjects
    let p1 = obj1 as Person
    let p2 = obj2 as Person
    return p1.name < p2.name
}

或者,使用NSArraysortedArrayUsingComparator:

var sortedArray = persons.sortedArrayUsingComparator {
    (obj1, obj2) -> NSComparisonResult in

    let p1 = obj1 as Person
    let p2 = obj2 as Person
    let result = p1.name.compare(p2.name)
    return result
}

这篇关于使用sortedArrayUsingComparator对NSArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:54