在swift中按字母顺序排序数组 [英] Sorting of an array alphabetically in swift

查看:981
本文介绍了在swift中按字母顺序排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是swift的新手。我正在尝试一个示例应用程序,其中我需要按字母顺序实现数组的排序。我得到json数据,我在数组中添加标题。现在我想按字母顺序排序。这是我的代码.....

I am new to swift.I am trying one sample app in which I need to implement the sorting of an array in alphabetical order.I getting the json data and I am adding the titles in the array.Now i would like to sort that alphabetically.Here is my code .....

func updateSearchResults(data: NSData?)
{
    do
    {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

            if let blogs: NSArray = json["results"] as? [AnyObject] {
                print(blogs)
                for blog in blogs {
                    if let name = blog["original_title"] as? String {
                        names.addObject(name)
                    }
                }
                print(names)
                **let sortedArray = sorted(names, {
                (str1: String, str2: String) -> Bool in
                return str1.toInt() < str2.toInt()** // Here I am getting the Error Message
                })

            }
    }
    catch {
        print("error serializing JSON: \(error)")
    }
}

我得到的错误消息是无法使用类型'的参数列表调用'sorted'(NSMutableArray,( String,String) - > Bool)'

我尝试了很多来实现这个目标,但我找不到解决方案。
任何人都可以帮我解决这个问题。
在此先感谢。

I tried a lot to achieve this but I didn't find the solution. Can anyone help me to resolve this issue. Thanks In Advance.

推荐答案

首先将 NSMutableArray 转换为使用下面的代码行使用Array。

First convert NSMutableArray to the Array by using below line of code.

 let swiftArray = mutableArray as AnyObject as! [String]

使用下面的代码行对数组进行排序。

Use below line of code to sort the Array.

var sortedArray = names.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

检查以下链接 sort 闭包。
https://developer.apple.com /library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

Check below link for sort Closures. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

Swift 3.0更新

Update for Swift 3.0

var sortedArray = swiftArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

这篇关于在swift中按字母顺序排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆