想要检查数组上是否存在对象

时间:2017-11-04 18:43:19

标签: arrays swift object

例如,我的数组看起来像这样

data.json

Questions("Question":"KEK1" , "Answers": ["", "", "", ""], "Answer": 1)
Questions("Question":"KEK2" , "Answers": ["", "", "", ""], "Answer": 1)
Questions("Question":"KEK3" , "Answers": ["", "", "", ""], "Answer": 1)
Questions("Question":"BAB1" , "Answers": ["", "", "", ""], "Answer": 1)
Questions("Question":"BAB2" , "Answers": ["", "", "", ""], "Answer": 1)
Questions("Question":"BAB3" , "Answers": ["", "", "", ""], "Answer": 1)

mycode的:

这是我使用red. data.json中的数据并将它们放在一个名为Questions

的数组中的代码
struct Question {
    var Question: String!
    var Answers: [String]!
    var Answer: Int!

    init(item: [String: Any])
    {
        self.Question = item["Question"] as? String
        self.Answers = item["Answers"] as? [String]
        self.Answer = item["Answer"] as? Int
    }
}

class LittleTestViewController: UIViewController {

var Questions = [Question]()
override func viewDidLoad() {
        super.viewDidLoad()
  jsonParsingQuestionsFile()
}

//parsing fata from json file
    func jsonParsingQuestionsFile ()
    {
        guard let path = Bundle.main.path(forResource: "data", ofType: "json"),
            let array = (try? JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe), options: JSONSerialization.ReadingOptions.allowFragments)) as? [[String : Any]] else{
                return
        }
        for item in array
        {
            self.Questions.append(Question(item: item))
        }
    }
}

我想看看数组中是否存在某些对象,然后执行某些操作。 例如:

var Questions = [Question]()
var kek = "KEK"
var bab = "BAB"

if kek exists on Questions
{
// do something
}else if bab exists on Questions
{
// do something
}else
{
// end
}

我想这就像Questions.contains...

1 个答案:

答案 0 :(得分:1)

您可能正在寻找filter。为了说明,我将大大简化。假设这个结构:

struct Question {
    let q: String
}

然后假设这个数组:

let questions = [Question(q:"KEK1"), Question(q:"KEK2"), 
    Question(q:"KEK3"), Question(q:"KEK4"), Question(q:"KEK5"), 
    Question(q:"KEK6"), Question(q:"KEK7"), Question(q:"KEK8"), 
    Question(q:"KEK9"), Question(q:"KEK10"), Question(q:"KEK11"), 
    Question(q:"BAB1"), Question(q:"BAB2"), Question(q:"BAB3"), 
    Question(q:"BAB4"), Question(q:"BAB5"), Question(q:"BAB6"), 
    Question(q:"BAB7"), Question(q:"BAB8"), Question(q:"BAB9"), 
    Question(q:"BAB10"), Question(q:"BAB11")]

现在让我们说问题是:从该阵列中,只获得KEK问题。我们可以使用filter

来做到这一点
let questionsWithKek = questions.filter{$0.q.contains("KEK")}
// result is: [Question(q: "KEK1"), Question(q: "KEK2"), Question(q: "KEK3"), 
//    Question(q: "KEK4"), Question(q: "KEK5"), Question(q: "KEK6"), 
//    Question(q: "KEK7"), Question(q: "KEK8"), Question(q: "KEK9"), 
//    Question(q: "KEK10"), Question(q: "KEK11")]

然后通过questionsWithKek循环并对每个人做一些事情是微不足道的。

如果问题确实是原始questions数组是否包含任何 KEK问题,那么只需查看questionsWithKek是否为空。