ios - 当我点击控制台检查输出时,xcode 崩溃

标签 ios xcode swift

遇到 xcode 问题。 我正在尝试开发一个可以为我提供天气信息的应用程序。构建成功,但每次我单击控制台检查输出(搜索、复制等)时,xcode 都会崩溃。

以下文字来自向 Apple 报告的工具,

应用程序特定信息: 产品版本:7C1002 未捕获异常(NSRangeException):-[__NSCFString characterAtIndex:]:范围或索引超出范围 用户信息:(空) 提示:无

这是我正在运行的代码,

override func viewDidLoad() {
super.viewDidLoad()

    let url = NSURL(string:"http://www.weather-forecast.com/locations/Hyderabad/forecasts/latest")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in

        if let webContent = data {

            let decodedContent = NSString(data: webContent, encoding: NSUTF8StringEncoding)
            //print(decodedContent)
            let weatherSiteSourceArray = decodedContent?.componentsSeparatedByString("3 Day Weather Forecast Summary:</b><span class=\"read-more-small\"><span class=\"read-more-content\"> <span class=\"phrase\">")
            print(weatherSiteSourceArray)

//                if weatherSiteSourceArray?.count > 0 { 
//                
//                    let weatherInfo = weatherSiteSourceArray![1]
//                    print(weatherInfo)
//                }
            }
    }
    task.resume()


    // Do any additional setup after loading the view, typically from a nib.
}

尽管报告工具通知我未捕获异常 (NSRangeException): -[__NSCFString characterAtIndex:]: 范围或索引超出范围。

我无法弄清楚这是在哪里发生的。 据我所知,您可以使用 print(items: Any...) 方法在 Swift 中打印数组。

对此的帮助将不胜感激!

最佳答案

您正在检查数组中是否有任何元素,然后尝试读取第二个元素。您的数组中可能只有一项,因此当您选择weatherSiteSourceArray![1]时,它会失败,因为访问元素 2 超出数组范围。

如果weatherSiteSourceArray?.count > 0 {

            let weatherInfo = weatherSiteSourceArray![1]

检查是否

     if weatherSiteSourceArray?.count > 1 

或使用第一个元素,即

          let weatherInfo = weatherSiteSourceArray![0]

我不知道 swift 并假设它使用基于零的数组索引。

关于ios - 当我点击控制台检查输出时,xcode 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36615154/

相关文章:

Xcode 源代码管理 - git add

ios - 解析和 Swift : How use advance targeting push to specific devices without users?

ios - NSInternalInconsistencyException 原因 : 'Invalid update: invalid number of rows in section 0'

ios - 在 Swift 中删除/排除枚举案例

iphone - 获取添加为 subview 的 UIView 的可见矩形

ios - 在 Swift 中使用静态函数来处理弹出窗口是不是很糟糕?

swift - 我的 Sprite 不执行我告诉它的操作?

ios - 在 Cocoapod 中导入 Kotlin/Native 框架

iphone - 在前向类对象上找不到属性?

swift - 如何在没有UI的情况下编写简单的Xcode Swift程序