无法在Swift中解包可选

时间:2014-06-08 18:03:20

标签: ios swift

此行 Can't unwrap Optional.None

上的运行时错误 let tfHppleElement = element.firstChild as TFHppleElement
func fetchDataToParse() {

    let urlToParse = NSURL.URLWithString("http://www.test.com/gotests")
    var err: NSError?
    let htmlData = NSData.dataWithContentsOfURL(urlToParse, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
        if (err) {
        NSLog("Error NSData.dataWithContentsOfURL, description: \(err.description)")
        return
        }
    let dataParser = TFHpple(HTMLData: htmlData)
    let xpathQueryString = "//div[@class='content-wrapper']/ul/li/a"
    let elements: Array = dataParser.searchWithXPathQuery(xpathQueryString)
        if elements.count == 0 {
        NSLog("No elemnts.count==0 in array  while searchWithXPathQuery ")
        return
        }

    var hrefValue:String?
    var titleValue:String?

        for element : AnyObject in elements{

            let tfHppleElement = element.firstChild as TFHppleElement
            titleValue = tfHppleElement.content

            if (titleValue){
                NSLog("\(titleValue)")
            }

            hrefValue = element.objectForKey("href")
            if (hrefValue){
             NSLog("\(hrefValue)")
             }



        }


}

1 个答案:

答案 0 :(得分:0)

element.firstChild可能为零,因此您应该在if语句中将其解包

if let tfHppleElement = element.firstChild? as? TFHppleElement
{
        titleValue = tfHppleElement.content

        if (titleValue){
            NSLog("\(titleValue)")
        }

        hrefValue = element.objectForKey("href")
        if (hrefValue){
         NSLog("\(hrefValue)")
         }
}

这样代码只会访问tfHppleElement(如果它存在并且可以强制转换为TFHppleElement