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

Tom
  • 513
  • 2
  • 5
  • 20

2 Answers2

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 
Eilon
  • 2,698
  • 3
  • 16
  • 32
  • 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! – Tom Feb 07 '20 at 20:30
  • 1
    Yep, I said you will have to manually remove the duplicates. This thread might help you with that: https://stackoverflow.com/questions/25738817/removing-duplicate-elements-from-an-array-in-swift – Eilon Feb 07 '20 at 21:02
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
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571