字典可选吗?快速混乱

时间:2014-07-14 11:25:50

标签: xcode swift ios8 optional xcode6

我知道这里有很多帖子,但我似乎无法弄清楚发生了什么。字典打印很好。它有一个单词列表,其中该单词的字母数为值。我想检查列表中是否有另一个字符串。我在选项上看了很多,但显然我错过了一些东西。我认为这当然与此有关。

    let path = NSBundle.mainBundle().pathForResource("wordlist", ofType: "txt")
    var content = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)?.componentsSeparatedByString("\n")



    var myDict = [String : Int]()



    let compareWord : String? = "TEST"

            if let content = content {
                for word in 100 ..< 105
                {
                    myDict[content[word]] = countElements(content[word])
                }
            }

    println("\(myDict)")



    var num : Int? = 0
    println("Num: \(myDict[compareWord!])")
    if let num : Int = myDict[compareWord!] {
        println("\(compareWord) is a word with \(num) letters")
    }
    else
    {
        println("Wasn't a word")
    }

****更新了代码的更多细节。


这是我打印字典部分时得到的结果。

[ABBOTSHIPS :11,ABBREVIATED :12,ABBOTS :7,ABBOTSHIP :10,ABBREVIATE :11]

如果我将测试单词设置为其中一个,我在检查时总是会得到nil。当我在操场下手动输入东西时似乎工作正常。

1 个答案:

答案 0 :(得分:1)

确保componentsSeparatedByString("\n")不会在每个提取的字符串的开头或结尾留下任何其他字符,例如\r