在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 }