我有一个从 plist 中提取的 testWords 数组/字典。我想随机打乱它们,取 2 的切片并将其 append 到另一个单词数组中。由于某种原因,我无法将 testWords append 到单词数组中。我还需要一个适用于 iOS8 的 random shuffle、select、append 版本。
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))
数组在控制台中看起来像这样:
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 '",
"",
""
)]
任何关于如何 append 这样一个数组的想法都非常感谢!现在回答了。
最佳答案
FirSTLy 前缀将返回一个 ArraySlice,它不是一个数组。
其次,append
方法向数组添加一个新元素。
因此,在您的情况下,您可以这样做:words.appendContentsOf(Array(chosenWords))
。
appendContentsOf
和 Array()
将从您的 ArraySlice
创建一个数组。
关于arrays - 如何获取数组/字典的切片并追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33599527/