ios - 如何通过制作单词列表文件的数组来确定数组中的每个元素是否包含某个字母(swift 2)

标签 ios arrays swift swift2

我对 swift 比较陌生。我正在尝试制作一个程序,该程序采用单词列表(以字符串数组的形式)并删除不包含用户选择的字母的字符串。所以,如果单词列表是 ["apple", "banana", "cherry", "date", "endive"] 并且用户选择字母“a”(这是变量“centerletter”),“apple”, “banana”和“date”将被返回,因为它们确实包含字母 a。当输入的数组 (wordlist) 是标准数组如 ["apple", "banana"] 时,此代码有效。但是,我对这段代码的实际用途是对英语中的每个单词进行排序,如我的文件“words.txt”(我的 swift 项目中的文件之一)中所见。

我已经将 words.txt 中的每个单词(由/n 分隔)分配给 wordlist,如下所示(这是函数):

func arrayFromContentsOfFileWithName(fileName: String) -> [String]? {

    let path = NSBundle.mainBundle().pathForResource("words", ofType: "txt")

    var fileContents: String? = nil
    do {
        fileContents = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
        return fileContents!.componentsSeparatedByString("\n")
    } catch _ as NSError {
        return nil
    }
}

我将 wordlist 分配给 arrayFromContentsOfFileWithName("words.txt") 的结果,如下所示:

var wordlist = arrayFromContentsOfFileWithName("words.txt")

然后我用这段代码处理单词列表(试图取出单词列表中不包含用户选择的字母(在我的示例中为“a”)的每个单词。这段代码适用于标准数组,如 ["apple", “香蕉”],但不在使用函数 arrayFromContentsOfFileWithName 制作的数组上。

let centerlet:Character = Character(Array(arrayLiteral: centerletter.text!)[0])

//centerlet是用户选择的字母。

    for var i = 0; i < wordlist?.count; i++ {
        if wordlist![i].characters.contains(centerlet) {
            print("I am leaving in \(wordlist![i]) because it contains the center letter")
        } else {
            print("I removed \(wordlist![i]) because it did not have the center letter.")
            wordlist?.removeAtIndex(i)
            }
        }

如何将 words.txt 中的所有单词转换为标准的 swift 数组,以便我可以删除所述数组中不包含特定字母的每个单词?谢谢。

最佳答案

您正在删除列表中的项目,同时使用索引遍历列表。在枚举列表的同时修改列表通常会导致灾难,并且通常会产生意想不到的结果。

一个简单的过滤器怎么样?

let filteredList = wordlist.filter { !$0.characters.contains(letter) }

关于ios - 如何通过制作单词列表文件的数组来确定数组中的每个元素是否包含某个字母(swift 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35166646/

相关文章:

iphone - SQLite 表名无效字符

javascript - 如何在返回之前等待迭代完成

ios - 自定义 UITableView 编辑模式

ios - 将 UIKit 的 UIScrollView 与 SpriteKit 结合使用

php - 从数据库读取值后显示选中和未选中的复选框列表不起作用

swift - 在应用程序启动时自动恢复上次保存的文档

ios - Google 地方信息未加载到 TableView 中

ios - 如果在 iOS 中按下按钮,如何禁用它?

ios - 适用于 iOS 的 Facebook SDK : FBSDKShareDialog is not shown

python - 在python中应用具有周期性边界条件的圆形掩模