线程 1:致命错误:索引超出范围

Posted

技术标签:

【中文标题】线程 1:致命错误:索引超出范围【英文标题】:Thread 1: Fatal error : Index out of Range 【发布时间】:2020-10-17 23:27:40 【问题描述】:

我正在尝试从 json 文件 data.json 中读取数据,但每当我尝试解析和显示数据时,我都会收到标题中提到的错误。

我正在尝试使用可编码协议解析 json,但似乎找不到给定错误的解决方案。

HomeTabViewController.swift

import UIKit
import FirebaseAuth

class HomeTabViewController: UIViewController,UITableViewDelegate,UITableViewDataSource 
    
    //MARK: - Global Variables
    
    var articles = [Article]()
    
    // MARK: - Outlets
    
    @IBOutlet weak var newsTableViewOutlet: UITableView!
    
    // MARK: - Default Functions

    override func viewDidLoad() 
        super.viewDidLoad()
        self.newsTableViewOutlet.dataSource = self
        self.newsTableViewOutlet.delegate = self

        if let localData = self.readLocalFile(forName: "data") 
            self.parse(json: localData)
        
    
    
    // MARK: - TableView Functions
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
        return articles.count
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        
        let cell = newsTableViewOutlet.dequeueReusableCell(withIdentifier: "newsCell", for: indexPath)
        let article = self.articles[indexPath.row]
        cell.textLabel?.text = article.title
        print(article.title)
        
        return cell
    
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) 
        let rotationTransform = CATransform3DTranslate(CATransform3DIdentity, 0, 30, 0)
        cell.layer.transform = rotationTransform
        cell.alpha = 0.5
        
        UIView.animate(withDuration: 0.75) 
            cell.layer.transform = CATransform3DIdentity
            cell.alpha = 1.0
        
    
    
    
    // MARK: - Data Download Functions
    
    // Function to parse JSON
    func parse(json: Data)
        let decoder = JSONDecoder()
        
        if let newsArticles = try? decoder.decode(Articles.self, from: json)
            self.articles = newsArticles.articles
            newsTableViewOutlet.reloadData()
        
    
    
    func readLocalFile(forName name: String) -> Data? 
        do 
            if let bundlePath = Bundle.main.path(forResource: name,
                                                 ofType: "json"),
                let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) 
                return jsonData
            
         catch 
            print(error)
        
        
        return nil
    
    
    // MARK: Segue Functions
    
    @IBAction func unwindToRootViewController(segue: UIStoryboardSegue) 
        print("Unwind to Root View Controller")
    
    
    @IBAction func logOutPressed(_ sender: UIButton) 
        print("Log out Button Pressed")
        
        let firebaseAuth = Auth.auth()
        do 
          try firebaseAuth.signOut()
         catch let signOutError as NSError 
          print ("Error signing out: %@", signOutError)
        
      
    

Article.swift

struct Article: Codable
    
    public var title: String
    public var description: String

Articles.swift

struct Articles: Codable 
    public var articles: [Article]

数据.json


"status": "ok",
"totalResults": 38,
"articles": [
,

"source": ,
"author": null,
"title": "Blair approves request to boost RCMP presence as Nova Scotia lobster fishery dispute escalates - CBC.ca",
"description": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitter conflict over a First Nations lobster harvest in that pro…",
"url": "https://www.cbc.ca/news/politics/nova-scotia-fishery-conflict-rcmp-1.5766838",
"urlToImage": "https://i.cbc.ca/1.5554196.1588555323!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/ns-shootings-20200420.jpg",
"publishedAt": "2020-10-17T21:16:00Z",
"content": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitt… [+4949 chars]"
,

"source": 
"id": null,
"name": "Maple Leafs Hot Stove"
,
"author": "Kevin Papetti",
"title": "Toronto Maple Leafs Offseason: Joe Thornton signing, the odd man out, and the next steps - Maple Leafs Hot Stove",
"description": "What an active week -- and offseason overall -- it's been for Kyle Dubas and the Toronto Maple Leafs. In: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey Anderson (RW), Travis Boyd (C/LW), Aaron Dell (G), Fi…",
"url": "https://mapleleafshotstove.com/2020/10/17/toronto-maple-leafs-offseason-joe-thornton-signing-the-odd-man-out-and-the-next-steps/",
"urlToImage": "https://46wvda23y0nl13db2j3bl1yx-wpengine.netdna-ssl.com/wp-content/uploads/2020/10/jumbo-joe-scaled.jpeg",
"publishedAt": "2020-10-17T20:39:00Z",
"content": "What an active week and offseason overall its been for Kyle Dubas and the Toronto Maple Leafs.\r\nIn: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey… [+10814 chars]"
,

"source": 
"id": null,
"name": "AppleInsider"
,
"author": "Malcolm Owen",
"title": "Early MagSafe Charger, iPhone 12 accessory orders start arriving - AppleInsider",
"description": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arriving ahead of the iPhone 12 range.",
"url": "https://appleinsider.com/articles/20/10/17/magsafe-chargers-iphone-12-accessory-orders-start-arriving-with-customers",
"urlToImage": "https://photos5.appleinsider.com/gallery/38304-72729-magsafe-charger-xl.jpg",
"publishedAt": "2020-10-17T19:46:39Z",
"content": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arr… [+1533 chars]"
,

"source": 
"id": null,
"name": "Global News"
,
"author": "Simon Little",
"title": "Anti-mask protesters cause disturbance on B.C. ferry, cause unloading delay - Global News",
"description": "A group of about 12 unmasked protesters became belligerent and harassed masked passengers on a morning sailing, according to BC Ferries.",
"url": "https://globalnews.ca/news/7403621/anti-mask-protesters-cause-disturbance-delay-b-c-ferry/",
"urlToImage": "https://globalnews.ca/wp-content/uploads/2018/02/01172660.jpg?quality=85&strip=all&crop=0px%2C111px%2C3000px%2C1579px&resize=720%2C379",
"publishedAt": "2020-10-17T19:30:51Z",
"content": "A group of anti-mask protesters has been banned from BC Ferries for the rest of the day after causing a disturbance on a morning sailing from Nanaimo to Horseshoe Bay.\r\nThe incident happened on the 8… [+2038 chars]"
,

"source": 
"id": "cbc-news",
"name": "CBC News"
,
"author": null,
"title": "Chechen teen killed by police named as suspect in teacher's beheading in France - CBC.ca",
"description": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on social media minutes after the attack, officials said Saturday.",
"url": "https://www.cbc.ca/news/world/france-teacher-beheading-chechen-1.5766742",
"urlToImage": "https://i.cbc.ca/1.5766755.1602956271!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/aptopix-france-teacher-decapitated.jpg",
"publishedAt": "2020-10-17T18:43:00Z",
"content": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on so… [+5743 chars]"



【问题讨论】:

与您的问题无关,但您为什么要读取字符串然后返回数据?只需加载数据并返回即可。 首先确保您使用的是有效的 JSON 嗯,我正在关注一个将其标记为良好实践的教程。我不知道它读取数据的方式是好是坏, 只需使用 contentsOf 初始化程序读取数据(如果它是 fileURL - 本地资源),如果您需要打印数据以进行调试,请使用 String(data: data, encoding: .utf8) ?? "") 【参考方案1】:

似乎 JSON 无效。我通过 jsonlint.com 运行它

我还删除了顶部的空文章。从 JSON 数据实例化 Article 时,这可能会导致问题。

这是固定版本:


    "status": "ok",
    "totalResults": 38,
    "articles": [
        
            "source": ,
            "author": null,
            "title": "Blair approves request to boost RCMP presence as Nova Scotia lobster fishery dispute escalates - CBC.ca",
            "description": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitter conflict over a First Nations lobster harvest in that pro…",
            "url": "https://www.cbc.ca/news/politics/nova-scotia-fishery-conflict-rcmp-1.5766838",
            "urlToImage": "https://i.cbc.ca/1.5554196.1588555323!/cpImage/httpImage/image.jpg_gen/derivatives/16x9_620/ns-shootings-20200420.jpg",
            "publishedAt": "2020-10-17T21:16:00Z",
            "content": "Public Safety Minister Bill Blair has greenlighted a request for additional RCMP support in Nova Scotia amid criticism that Ottawa has not done enough to protect community members embroiled in a bitt… [+4949 chars]"
        ,
        
            "source": 
                "id": null,
                "name": "Maple Leafs Hot Stove"
            ,
            "author": "Kevin Papetti",
            "title": "Toronto Maple Leafs Offseason: Joe Thornton signing, the odd man out, and the next steps - Maple Leafs Hot Stove",
            "description": "What an active week -- and offseason overall -- it's been for Kyle Dubas and the Toronto Maple Leafs. In: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey Anderson (RW), Travis Boyd (C/LW), Aaron Dell (G), Fi…",
            "url": "https://mapleleafshotstove.com/2020/10/17/toronto-maple-leafs-offseason-joe-thornton-signing-the-odd-man-out-and-the-next-steps/",
            "urlToImage": "https://46wvda23y0nl13db2j3bl1yx-wpengine.netdna-ssl.com/wp-content/uploads/2020/10/jumbo-joe-scaled.jpeg",
            "publishedAt": "2020-10-17T20:39:00Z",
            "content": "What an active week and offseason overall its been for Kyle Dubas and the Toronto Maple Leafs.\r\nIn: T.J. Brodie (RD), Wayne Simmonds (RW), Zach Bogosian (RD), Joe Thornton (C), Jimmy Vesey (LW), Joey… [+10814 chars]"
        ,
        
            "source": 
                "id": null,
                "name": "AppleInsider"
            ,
            "author": "Malcolm Owen",
            "title": "Early MagSafe Charger, iPhone 12 accessory orders start arriving - AppleInsider",
            "description": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arriving ahead of the iPhone 12 range.",
            "url": "https://appleinsider.com/articles/20/10/17/magsafe-chargers-iphone-12-accessory-orders-start-arriving-with-customers",
            "urlToImage": "https://photos5.appleinsider.com/gallery/38304-72729-magsafe-charger-xl.jpg",
            "publishedAt": "2020-10-17T19:46:39Z",
            "content": "A number of Apple cusomers are already seeing products announced during Apple's second special event arrive on their doorsteps, with MagSafe chargers, the 20W USB-C power adapter, and other items arr… [+1533 chars]"
        ,
        
            "source": 
                "id": null,
                "name": "Global News"
            ,
            "author": "Simon Little",
            "title": "Anti-mask protesters cause disturbance on B.C. ferry, cause unloading delay - Global News",
            "description": "A group of about 12 unmasked protesters became belligerent and harassed masked passengers on a morning sailing, according to BC Ferries.",
            "url": "https://globalnews.ca/news/7403621/anti-mask-protesters-cause-disturbance-delay-b-c-ferry/",
            "urlToImage": "https://globalnews.ca/wp-content/uploads/2018/02/01172660.jpg?quality=85&strip=all&crop=0px%2C111px%2C3000px%2C1579px&resize=720%2C379",
            "publishedAt": "2020-10-17T19:30:51Z",
            "content": "A group of anti-mask protesters has been banned from BC Ferries for the rest of the day after causing a disturbance on a morning sailing from Nanaimo to Horseshoe Bay.\r\nThe incident happened on the 8… [+2038 chars]"
        ,
        
            "source": 
                "id": "cbc-news",
                "name": "CBC News"
            ,
            "author": null,
            "title": "Chechen teen killed by police named as suspect in teacher's beheading in France - CBC.ca",
            "description": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on social media minutes after the attack, officials said Saturday.",
            "url": "https://www.cbc.ca/news/world/france-teacher-beheading-chechen-1.5766742",
            "urlToImage": "https://i.cbc.ca/1.5766755.1602956271!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/aptopix-france-teacher-decapitated.jpg",
            "publishedAt": "2020-10-17T18:43:00Z",
            "content": "A suspect shot dead by police after the beheading of a history teacher near Paris was an 18-year-old Chechen refugee unknown to intelligence services who posted a grisly claim of responsibility on so… [+5743 chars]"
        
    ]

编辑:我添加了working gist

【讨论】:

我用固定的 json 再次运行程序,现在我得到这个 ``` 致命错误:索引超出范围:文件 Swift/ContiguousArrayBuffer.swift,第 444 行 2020-10-17 23:42 :31.454115-0400-Project[6613:139237] 致命错误:索引超出范围:文件 Swift/ContiguousArrayBuffer.swift,第 444 行``` 我为一个正在读取 JSON 数据的游乐场添加了一个要点。 你能启用异常和快速错误断点吗?它会告诉你这个异常是由哪里引起的。

以上是关于线程 1:致命错误:索引超出范围的主要内容,如果未能解决你的问题,请参考以下文章

将代码更新为最新的 Swift 4 语法会导致“线程 1:致命错误:索引超出范围”错误

准备转场时致命错误索引超出范围

我收到错误:致命错误:索引超出范围

Swift 致命错误:数组索引超出范围

Swift 致命错误:数组索引超出范围

致命错误 索引超出范围