我有一個問題,不幸的是沒有找到任何反應。如何從第二個數組中的第一個數組中找到對象? Swift iOS
我會用一個簡單的例子來描述這個問題。我有一個對象數組。每個對象都包含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.
}
}
是否想通過名稱檢查id的名稱或按count數? – Daljeet
我想在第一個數組中找到第二個數組中的對象。 – Maselko
如果你用一個例子來解釋,我很容易引導你。 – Daljeet