【问题标题】:How to take a slice of an array / dictionary and append如何获取数组/字典的一部分并追加
【发布时间】:2016-02-09 12:46:36
【问题描述】:

我有一个从 plist 中提取的 testWords 数组/字典。我想随机打乱它们,取一片 2 并将其附加到另一个单词数组中。出于某种原因,我无法将 testWords 附加到 words 数组中。我还需要 iOS8 的随机 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 '",
"",
""
)] 

任何关于如何附加这样一个数组的想法都非常感谢!现在回答了。

【问题讨论】:

    标签: arrays swift dictionary append slice


    【解决方案1】:

    首先前缀将返回一个 ArraySlice,它不是一个数组。 其次,append 方法向数组中添加了一个新元素。

    所以在你的情况下你可以这样做:words.appendContentsOf(Array(chosenWords))appendContentsOf Array() 将从您的 ArraySlice 创建一个数组。

    【讨论】:

    • 感谢济科。我还添加了 let selectedWords = Array(shuffledTestWords.prefix(2))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    相关资源
    最近更新 更多