如何检查复杂数组中的相似数据

时间:2018-07-07 17:32:21

标签: arrays swift if-statement key-value

在这里,我得到一个随机用户,并替换了users数组中的一个用户。但是,我想检查一下我是否刚刚从random1那里获得了该用户。我想按他们的身份证件检查。我知道它必须是一个if语句,但是我不知道如何实际检查它是否包含在用户中。另外,在if语句的主体中,我将必须进行递归。如果我再次调用自身,是否可以只传递getRandom1(index:index),还是会不记得我最初调用它时的索引是什么?

 struct User: Decodable {
var id: Int
var first_name: String
var last_name: String
var picture_url: String
var points: Int
var school: String
var grade: Int
}

var users = [User]()

func getRandom8() {
let url = URL(string: "https://somewebsite.com/users/random/eight")
let session = URLSession.shared

let request = NSMutableURLRequest(url: url!)
let preferences = UserDefaults.standard
request.addValue("JWT \(preferences.object(forKey: "token") as! String)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"

let task = session.dataTask(with: request as URLRequest, completionHandler: {
    (data, response, error) in
    do {
        self.users = try JSONDecoder().decode([User].self, from: data!)

        DispatchQueue.main.async (
            execute: self.loadRandom8
        )

    } catch {
        print("error in getting data")
    }
})

task.resume()

}

func getRandom1(index:Int) {
let url = URL(string: "https://somewebsite.com/users/random/one")
let session = URLSession.shared

let request = NSMutableURLRequest(url: url!)
let preferences = UserDefaults.standard
request.addValue("JWT \(preferences.object(forKey: "token") as! String)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "GET"
//write a statement that says if that user is already there, do the call again
let task = session.dataTask(with: request as URLRequest, completionHandler: {
    (data, response, error) in

    do {
        let user = try JSONDecoder().decode(User.self, from: data!)
            self.users[index] = user

//if statement should go here
        DispatchQueue.main.async (
            execute: self.loadRandom8
        )

    } catch {
        print("error in getting data")
    }
})

task.resume()

}

1 个答案:

答案 0 :(得分:1)

您可以尝试

if users.contains(user) {
   // user in the array
}

还要确保对Equatable实施User协议