ios - 如何使用 Swift 实现数组过滤器?

标签 ios swift

我正在使用 Alamofire 和 SwiftyJSON 解析 JSON。 TableView Controller 工作得非常好,但我需要消除/过滤一些对象。就像如果字典数组中具有“id”(即“1”)的对象持续存在,则应该对其进行过滤。

这是 JSON 数据的样子:

[
{
    "id": 1,
    "title": "item1",
    "created_at": "2014-08-30T15:50:38.421Z",
    "updated_at": "2014-08-30T15:50:38.421Z"
},
{
    "id": 2,
    "title": "item2",
    "created_at": "2014-08-30T15:50:38.453Z",
    "updated_at": "2014-08-30T15:50:38.453Z"
},
{
    "id": 3,
    "title": "item3",
    "created_at": "2014-08-30T15:50:38.464Z",
    "updated_at": "2014-08-30T15:50:38.464Z"
},
]

这是 TableView Controller 的样子:

import UIKit
import Alamofire

class ViewController: UITableViewController {

    var items: Array<Item>?
    var username: JSON!
    var id: JSON!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        items = Array()

        Alamofire.request(.GET, "http://brownbro-json-api-test.herokuapp.com/api/items")
            .responseJSON {(request, response, JSONresponse, error) in
                let result = JSON(JSONresponse!)

                for (var i = 0; i < result.arrayValue.count; i++) {
                    var item: Item = Item (
                        id: result[i]["id"].stringValue,
                        title: result[i]["title"].stringValue,
                        detail: "detail",
                        imageURL: "http://japan.cnet.com/storage/2013/11/14/98b86da26f62c9e12c07f1d49932d6eb/131114_wemake_180x135.jpg"
                    )
                    self.items?.append(item)
                }
                self.tableView.reloadData()
            }
    }    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section:    Int) -> Int {
        //return 10
        return self.items!.count
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 100;
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "ItemCell")

        cell.textLabel!.text = self.items?[indexPath.row].title
        cell.detailTextLabel!.text = self.items?[indexPath.row].detail


        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> () in
            var imageURL: NSURL = NSURL(fileURLWithPath: self.items![indexPath.row].imageURL)!
           // var imageData: NSData = NSData(contentsOfURL: imageURL)!
           // var image: UIImage = UIImage(data: imageData)!

            dispatch_async(dispatch_get_main_queue(), { () -> () in
                //cell.imageView!.image = image
            })
        })
        return cell
    }

    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
        performSegueWithIdentifier("show_detail", sender: indexPath)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "show_detail" {
            var indexPath : NSIndexPath = sender as! NSIndexPath
            var item_id : String = self.items![indexPath.row].id
            var DVController = segue.destinationViewController as! DetailViewController
            DVController.item_id = item_id
        }
    }
}

这是项目对象:

import UIKit

class Item: NSObject {
    var id: String, title: String, detail: String, imageURL: String

    init(id: String, title: String, detail: String, imageURL: String) {
        self.id = id
        self.title = title
        self.detail = detail
        self.imageURL = imageURL
    }
}

我不知道如何过滤某些行。

最佳答案

你可以像这样获取不带'id == "1"'的项目。

var items: [Item] = ...
items = items.filter { $0.id != "1"} // This will eliminate items with id == "1".
// it is equivalent to the below line
items = items.filter({ (item:Item)->Bool in item.id != "1"})

不要忘记在更改项目后调用 tableView.reloadData()

关于ios - 如何使用 Swift 实现数组过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32165523/

相关文章:

ios - 如何从后台的iOS应用程序在后台保存解析对象?

ios - Swift 3 将数据从一个 ViewController 传递到另一个 ViewController

Swift:覆盖子类中的类型别名

ios - 无法使用swift访问tabBar项目的索引

Swift - 搜索数据未加载

ios - 更新 iOS 11 中的左侧导航项目

ios - Swift-获取自计时器启动以来经过了多少秒/毫秒

ios - 如何在 Alamofire Swift 中刷新 JWT token 状态代码 500

ios - 无法将类型 'FriendTableViewCell.Type' 的值转换为预期的参数类型 'FriendTableViewCell'

objective-c - 无法在 iOS 中隐藏键盘