0

Had a search here but most answers seem to relate to Boolean values. I have a struct defined and initialised as below:

Struct Question {
   var subjectID: Int
   var questionID: Int
}

//Examples
let questionOne = Question(subjectID: 0, questionID: 0)
let questionTwo = Question(subjectID: 0, questionID: 1)
let questionThree = Question(subjectID: 0, questionID: 2)
let questionFour = Question(subjectID: 1, questionID: 0)

//An array populated with the above
var questions = [Question]()

I would like to find how to calculate:

1) The number of unique subjectID values in questions Array. Answer should be 2.

2) The number of questions in questions Array where subjectID == 0, or 1. Answer should be [3, 1].

I have explored with .filter and .map but perhaps I'm on the wrong tangent? Thanks

0

2 Answers 2

1

For 1) you would manually filter out duplicate values. You can get an array of all the subjectIDs with .map like so:

let subjectIDs = questions.map { $0.subjectID } 

For 2), you can simply use the .filter function like so:

let subjectIdXCount = questions.filter { $0.subjectID == x }.count 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply but the first part (.map) doesn't filter out duplicates, it returns an array of [0, 0, 0, 1]. The second part works great though, thanks!
Yep, I said you will have to manually remove the duplicates. This thread might help you with that: stackoverflow.com/questions/25738817/…
1

You should use collection's reducemethod and increase the initialResult in case nextPartialResult meets your criteria:

struct Question {
   var subjectID: Int
   var questionID: Int
}

let questionOne = Question(subjectID: 0, questionID: 0)
let questionTwo = Question(subjectID: 0, questionID: 1)
let questionThree = Question(subjectID: 0, questionID: 2)
let questionFour = Question(subjectID: 1, questionID: 0)

let questions = [questionOne, questionTwo, questionThree, questionFour]

let subjectCount = questions.reduce(0) { $0 + ($1.subjectID == 0 ? 1 : 0 )}

print(subjectCount)  // 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.