按键值排序字典数组

时间:2016-01-12 14:04:09

标签: ios arrays swift sorting dictionary

我有一个字典数组,我想通过每个字典中的“itemName”键按字母顺序对它们进行排序。我怎么能在Swift中做到这一点?

我想对itemsArray进行排序。

let array = PFUser.currentUser()?.objectForKey("Collections") as! [[String : AnyObject]]
        let collectionsDictionary = array[0]
        itemsArray = collectionsDictionary[self.title!] as! [[String : AnyObject]]


        for dictionary in itemsArray {
            itemNames.append(dictionary["itemName"] as! String)
            itemUPC.append(dictionary["UPC"] as! String)
            pricePaid.append(dictionary["pricePaid"] as! String)
            currentPrice.append(dictionary["currentPrice"] as! String)
            model.append(dictionary["model"] as! String)
            if (dictionary["image"] != nil) {
                imagesArray.append(dictionary["image"] as! PFFile)
            } else {
                imagesArray.append(nil)
            }
        }

5 个答案:

答案 0 :(得分:16)

可能是这样的,使用sort

let sortedArray = itemsArray.sort { $0["itemName"] < $1["itemName"] }

其中“$ 0”和“$ 1”分别代表数组中的每个字典及其后继字符。

如果编译器抱怨这些类型,因为它不知道这个键的值是一个String,你可以像这样进行投射(如评论中的@Cristik所说):

let sortedArray = itemsArray.sort { ($0["itemName"] as? String) < ($1["itemName"] as? String) }

答案 1 :(得分:14)

您可以使用NSArray的{​​{1}}功能:

sortUsingDescriptors

Swift&gt; 3

let sortedArray = (itemsArray as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "itemName", ascending: true)]) as [[String:AnyObject]]

不是非常迅速,你失去了类型的安全性,但它确实起到了作用。

顺便说一下,你的代码中有很多强制转换,有可能导致应用程序崩溃,你应该考虑切换到可选代码。

答案 2 :(得分:1)

这对我有用:

let descriptor: NSSortDescriptor = NSSortDescriptor(key: "itemName", ascending: true)
let sortedResults: NSArray = favArray.sortedArray(using: [descriptor]) as NSArray

答案 3 :(得分:0)

我有一个字典数组,我按字母顺序排序&#34; firstname&#34;每个字典中的键。您还可以通过将数组名称放在此代码和keyName

中来对数组进行排序

/ *

+ (UIImage *) convertBitmapRGBA8ToUIImage:(unsigned char *) buffer
                            withWidth:(int) width
                           withHeight:(int) height {

 char* rgba = (char*)malloc(width*height*4);
for(int i=0; i < width*height; ++i) {
    rgba[4*i] = buffer[4*i];
    rgba[4*i+1] = buffer[4*i+1];
    rgba[4*i+2] = buffer[4*i+2];
    rgba[4*i+3] = buffer[4*i+3];
}
//


size_t bufferLength = width * height * 4;
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, rgba, bufferLength, NULL);
size_t bitsPerComponent = 8;
size_t bitsPerPixel = 32;
size_t bytesPerRow = 4 * width;

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
  if(colorSpaceRef == NULL) {
    NSLog(@"Error allocating color space");
    CGDataProviderRelease(provider);
    return nil;
}

CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedFirst;

CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
CGImageRef iref = CGImageCreate(width,
                                height,
                                bitsPerComponent,
                                bitsPerPixel,
                                bytesPerRow,
                                colorSpaceRef,
                                bitmapInfo,
                                provider,
                                NULL,
                                YES,
                                renderingIntent);

uint32_t* pixels = (uint32_t*)malloc(bufferLength);

if(pixels == NULL) {
    NSLog(@"Error: Memory not allocated for bitmap");
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorSpaceRef);
    CGImageRelease(iref);
    return nil;
}

CGContextRef context = CGBitmapContextCreate(pixels,
                                             width,
                                             height,
                                             bitsPerComponent,
                                             bytesPerRow,
                                             colorSpaceRef,
                                             bitmapInfo);

if(context == NULL) {
    NSLog(@"Error context not created");
    free(pixels);
}

UIImage *image = nil;
if(context) {

    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), iref);

    CGImageRef imageRef = CGBitmapContextCreateImage(context);

    image = [UIImage imageWithCGImage:imageRef];

    CGImageRelease(imageRef);
    CGContextRelease(context);
}

CGColorSpaceRelease(colorSpaceRef);
CGImageRelease(iref);
CGDataProviderRelease(provider);


if(pixels) {
    free(pixels);
}   
return image;

* /

希望它可以帮到你。

答案 4 :(得分:0)

&#39; $&#39; /// items是字典数组 / *

let items: [[String: Any]] = [
   ["itemName":"ZZ_Item", "itemDescription":"Homer"],
   ["itemName":"AA_Item", "itemDescription":"Marge"],
   ["itemName":"VV_Item", "itemDescription":"Bart"],
   ["itemName":"BB_Item", "itemDescription":"Lisa"],
   ["itemName":"XY_Item", "itemDescription":"Maggie"],
   ["itemName":"CC_Item", "itemDescription":"Ned"]
]
print(items)

* / /// O / P un_sorted array

/// [[&#34; itemName&#34;:&#34; ZZ_Item&#34;,&#34; itemDescription&#34;:&#34; Homer&#34;],[&#34; itemName&#34;:& #34; AA_Item&#34;,&#34; itemDescription&#34;:&#34; Marge&#34;],[&#34; itemName&#34;:&#34; VV_Item&#34;,&#34; itemDescription&#34;:&#34; Bart&#34;],[&#34; itemName&#34;:&#34; BB_Item&#34;,&#34; itemDescription&#34;:&#34; Lisa&#34 ;],[&#34; itemName&#34;:&#34; XY_Item&#34;,&#34; itemDescription&#34;:&#34; Maggie&#34;],[&#34; itemName&#34; :&#34; CC_Item&#34;,&#34; itemDescription&#34;:&#34; Ned&#34;]]

///按itemsName键排序数组

func itemsSort(p1:[String:Any], p2:[String:Any]) -> Bool {
    guard let s1 = p1["itemName"] as? String, let s2 = p2["itemName"] as? String else {
        return false
    }
    return s1 < s2
}

let sortedItemsArray = items.sorted { itemsSort(p1:$0, p2:$1) }
print(sortedItemsArray)

//// O / P排序数组

[[&#34; itemName&#34;:&#34; AA_Item&#34;,&#34; itemDescription&#34;:&#34; Marge&#34;],[&#34; itemName&#34 ;:&#34; BB_Item&#34;,&#34; itemDescription&#34;:&#34; Lisa&#34;],[&#34; itemName&#34;:&#34; CC_Item&#34;,& #34; itemDescription&#34;:&#34; Ned&#34;],[&#34; itemName&#34;:&#34; VV_Item&#34;,&#34; itemDescription&#34;:&#34; Bart&#34;],[&#34; itemName&#34;:&#34; XY_Item&#34;,&#34; itemDescription&#34;:&#34; Maggie&#34;],[&#34; itemName& #34;:&#34; ZZ_Item&#34;,&#34; itemDescription&#34;:&#34; Homer&#34;]]