在Objective-C中,我可以使用以下语句对NSArray进行排序:
NSArray *sortedArray = [persons sortedArrayUsingComparator:^NSComparisonResult(Person *p1,Person *p2) { return [p1.name compare:p2.name]; }];
我无法用Swift再现同样的声明。我发现我使用的是Array。
您可以使用
Swift’s built in sort functions,或者由于将Swift阵列桥接到NSArray,您可以直接从swift调用sortedArrayUsingComparator。
原文链接:https://www.f2er.com/swift/320465.html使用Swift的排序功能:
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 }
或者,使用NSArray的sortedArrayUsingComparator:
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 }