Reputation: 962
I'm trying to sort and then cut 20 quiz questions from an array containing 50. The quiz questions are dictionaries.
var quizQuestionsRaw = [[String:String]]()
var quizQuestions = [[String:String]]()
quizQuestionsRaw = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: quizQuestionsRaw) as! [[String:String]]
Then I tried
quizQuestions = quizQuestionsRaw.removeFirst(30) as! [[String:String]]
But I just got an error. Can someone help with that? Thanks.
Upvotes: 1
Views: 43
Reputation: 346
Ok, Try this..
//First We'll Create an Extension to Shuffle Array
extension Array
{
mutating func shuffle()
{
for _ in 0..<10
{
sort { (_,_) in arc4random() < arc4random() }
}
}
}
// Replace this Array of Dictionary With your Q&A Array
var array:[[String: String]] = [["Q1":"A1"],["Q2":"A2"],["Q3":"A3"],["Q4":"A4"],["Q5":"A5"]....["Q30":"A30"]]
array.shuffle()
// This line will return last 20 elements of array
array.suffix(20)
If you're using Swift 4.2 or later version you don't need to create an extension to shuffle array in that case, this line is sufficient
array.shuffled()
Good Luck :)
Upvotes: 2