如何从第二个数组中的第一个数组中查找对象? Swift iOS

时间:2015-07-21 06:17:13

标签: ios arrays swift parsing compare

我有一个问题,遗憾的是没有找到任何答案。

我将在一个简单的例子中描述这个问题。我有一个对象数组。每个对象都包含id,name,count。此数组是从服务器解析数据的结果。它被视为第一个。

我还从另一台服务器获取了第二个数组。这是相同的数组ID,名称,计数。

我的问题如下。第一个数组有20个元素,然后我想要将这个元素中的每个元素与另一个元素的数组进行比较。第二个数组是解析。您可能需要使用循环并检查第一个数组中的每个元素是否都在第二个?

//
//  ViewController.swift
//  ParseSearching
//
//  Created by Mateusz Fraczek on 21.07.2015.
//  Copyright (c) 2015 universeldev. All rights reserved.
//

import UIKit
import Parse

struct Model : Equatable {
    var ide: String!
    var name: String!
    var count: String!
}

func ==(a: Model, b: Model) -> Bool {
    return a.ide == b.ide && a.name == b.name && a.count == b.count
}

extension Array {

    func indexesOfSubset<T : Equatable>(objects : [T]) -> [Int] {

        // Create storage for filtered objects and results
        var unusedObjects = objects
        var result : [Int] = []

        // Enumerate through all objects in array
        for (index, obj) in enumerate(self) {

            // Enumerate again through all objects that has not been found
            for x in unusedObjects {

                // If we hit match, append result, remove it from usused objects
                if obj as! T == x {
                    result.append(index)
                    unusedObjects = unusedObjects.filter( { $0 != x } )
                    break
                }
            }
        }

        // Get results
        return result
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var firstArray = [Model]()
        var resultsArray = [Model]()


        firstArray.append(Model(ide: "xyz1", name: "name1", count: "0"))
        firstArray.append(Model(ide: "xyz2", name: "name2", count: "0"))
        firstArray.append(Model(ide: "xyz3", name: "name3", count: "0"))
        firstArray.append(Model(ide: "xyz4", name: "name4", count: "0"))

//        let testObject = PFObject(className: "TestObject")
//        testObject["ide"] = "xyz1"
//        testObject["name"] = "name1"
//        testObject["count"] = "0"
//        testObject.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
//            println("Object has been saved.")
//        }


        var query = PFQuery(className: "TestObject")

        query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
            if let object = objects as? [PFObject] {
                for obj in object {
                    var id = obj.objectForKey("ide") as! String
                    var name = obj.objectForKey("name") as! String
                    var count = obj.objectForKey("count") as! String

                    var model = Model(ide: id, name: name, count: count)

                    resultsArray.append(model)
                    println(resultsArray)
                    let indexes = firstArray.indexesOfSubset(resultsArray)

                    println("Indexes \(indexes) ")
                }
            }
        }



    }

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



}

4 个答案:

答案 0 :(得分:1)

您可以这样做:

斯威夫特1:

var array = ["1", "2", "3"]
var contained = contains(array, "2")
println(contained ? "yes" : "no")

斯威夫特2:

var array = ["1", "2", "3"]
var contained = array.contains("2")
println(contained ? "yes" : "no")

答案 1 :(得分:0)

我绝不是专家,但我会在NSarray class内使用isEqualToArray。

类中的函数将接收数组与另一个数组进行比较。

SWIFT
func isEqualToArray(_ otherArray: [AnyObject]) -> Bool

返回值
如果otherArray的内容等于接收数组的内容,则为YES,否则为NO

答案 2 :(得分:0)

为了找到子集的索引,最好在SWIFT中使用新的东西,你怎么说?因此,让我们使用泛型并制作将来可用的解决方案,当您的对象发生变化时,或者您将完全使用不同的对象。让我们为你的数组创建扩展:

extension Array {

    func indexesOfSubset<T : Equatable>(objects : [T]) -> [Int] {

        // Create storage for filtered objects and results
        var unusedObjects = objects
        var result : [Int] = []

        // Enumerate through all objects in array
        for (index, obj) in enumerate(self) {

            // Enumerate again through all objects that has not been found
            for x in unusedObjects {

                // If we hit match, append result, remove it from usused objects
                if obj as! T == x {
                    result.append(index)
                    unusedObjects = unusedObjects.filter( { $0 != x } )
                    break
                }
            }
        }

        // Get results
        return result
    }
}

现在您可以使用此方法查找对象:

let sameIndexes = allData.indexesOfSubset(fetchedData)

当然,在您的情况下[模型],获取的数据和所有数据必须是相同的数据类型。您还必须确保可以正确地比较这两个对象,为此,您必须创建比较器,采用如下数据类型:

public func ==(a: Model, b: Model) -> Bool {
    return a.id == b.id && a.name == b.name && a.count == b.count
}

此外,为了使其工作,您必须使您的对象符合Equatable协议,所以这样做:

struct Model : Equatable {

现在当你比较两个相同的Model对象时,你会得到compare == true而不是错误:)希望它有所帮助!

编辑: Here is test gist您可以在其中找到所有内容,包括评论中的内容+如何使用

答案 3 :(得分:0)

使用过滤器并包含

func == (lhs: SomeStruct, rhs: SomeStruct) -> Bool {
    return lhs.intConstant == rhs.intConstant && lhs.stringConstant == rhs.stringConstant
}

struct SomeStruct: Equatable {
    let intConstant:Int
    let stringConstant:String
}

var someStructOne = SomeStruct(intConstant: 1, stringConstant: "1")
var someStructTwo = SomeStruct(intConstant: 2, stringConstant: "2")
var someStructThree = SomeStruct(intConstant: 3, stringConstant: "4")
var someStructFour = SomeStruct(intConstant: 4, stringConstant: "4")
var someStructFive = SomeStruct(intConstant: 5, stringConstant: "5")


let structArrayOne = [someStructOne, someStructTwo, someStructThree]
let structArrayTwo = [someStructOne, someStructFour, someStructFive]

let structsInBothArrays = structArrayOne.filter({contains(structArrayTwo, $0)})

这里的技巧是使结构符合Equatable ptotocol。您可以使用顶部的全局函数定义执行此操作,该定义提供了如何比较两个结构的定义。