0

I have an array / dictionary of testWords that is pulled from a plist. I want to randomly shuffle them, take a slice of 2 and append that to another words array. For some reason I can't append the testWords to the words array. I also need a version of the random shuffle, select, append for iOS8.

var words: [NSArray]

var testWords: [NSArray]!

let fileName = "level\(levelNumber).plist"
let levelPath = "\(NSBundle.mainBundle().resourcePath!)/\(fileName)"
let levelDictionary: NSDictionary? = NSDictionary(contentsOfFile: levelPath)
testWords = levelDictionary!["words"] as! [NSArray]

let shuffledTestWords = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(testWords)
         print("testWords after shuffling is \(shuffledTestWords)")

let chosenWords = Array(shuffledTestWords.prefix(2))
words.appendContentsOf(Array(chosenWords)) 

The array looks like this in the console:

testWords after shuffling is [(
"drinc drink",
drink,
"Which one is right?",
"",
""
), (
"bank banc",
bank,
"Spell this word ending in  ' nk '",
"",
""
), (
"bunk bunc",
bunk,
"Spell this word ending in  ' nk '",
"",
""
)] 

Any ideas on how to append such an array much appreciated! Now answered.

1 Answer 1

0

Firstly prefix will return an ArraySlice, which is not an array. Secondly the append method add one new element to the array.

So in your case you could do: words.appendContentsOf(Array(chosenWords)). appendContentsOf and Array() will create an array from your ArraySlice.

1
  • Thanks Zico. I also added let chosenWords = Array(shuffledTestWords.prefix(2))
    – richc
    Commented Nov 9, 2015 at 9:21

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.