首页 > 解决方案 > For 循环不超出 else { continue }

问题描述

我第一次尝试使用 JSON 数据,我真的很挣扎。我想在带有一些标签的 UIView 中显示数据,但是当我在 else { continue } 行之后添加一些断点时,step thru 过程会直接过去 else { continue } 并在该点之后继续过去我的所有代码,所以员工永远不会添加到我的对象中,我也无法通过 print() 方法打印代码来确认我的代码是否有效。我还遇到以下错误:无法将类型“[String:Any]”的值转换为预期的参数类型“[String]?”

我不确定我能做些什么来解决这个问题,任何建议都将不胜感激。

这是我的 ViewController.swift 文件的代码:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var empName: UILabel!
    @IBOutlet weak var empUsername: UILabel!
    @IBOutlet weak var empSkills: UILabel!
    @IBOutlet weak var pastEmployers: UILabel!
    @IBOutlet weak var textFieldNote: UITextField!
    
    var employees = [Employee]() // An empty array of employees
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // Get the path to the EmployeeData.json file
        if let path = Bundle.main.path(forResource: "EmployeeData", ofType: ".json" ) {
            let url = URL(fileURLWithPath: path)
            
            do {
                // Create a data object from the files url
                // After this line executes, our file is in binary format inside the "data" constant
                let data = try Data.init(contentsOf: url)
                
                // Create a json Object from the binary Data file.
                // Catch it as an array of Any type objects
                let jsonObj = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [Any]
                
                // At this point we have an array of Any objects that represents our JSON data from our file
                // We can now parse through the jsonObj and start instantiating our Employee objects.
                Parse(jsonObject: jsonObj)
            }
            catch {
                print(error)
            }
        }
    }

    func Parse(jsonObject: [Any]?) {
        
        guard let json = jsonObject
        else {print("Parse failed to unwrap the optional."); return }
        
        // Looping through the first level objects
        for firstLevelItems in json {
            // Try to convert first level object into a [String: Any]
            guard let object = firstLevelItems as? [String: Any],
                  let ename = object["employeename"] as? String,
                  let eusername = object["username"] as? String,
                  let emacaddress = object["macaddress"] as? String,
                  let ecurrentTitle = object["current_title"] as? String,
                  let eskills = object["skills"] as? [String],
                  let epastEmployers = object["past_employers"] as? [String: Any],
                  let pcompany = epastEmployers["company"] as? String,
                  let presponsibilities = epastEmployers["responsibilities"] as? String,
                  let ecompany = object["company"] as? String,
                  let eresponsibilities = object["responsibilities"] as? [String]
            // if anything in the guard fails, immediately continue to the next iteration of the loop
            else { continue }
            
 
            
            employees.append(Employee(name: ename, username: eusername, macaddress: emacaddress, currentTitle: ecurrentTitle, skills: eskills, pastEmployers: epastEmployers, currentCompany: ecompany, responsibilities: eresponsibilities))
            
  
            
           // Build Object here
            
            //Check to see if this current employee exists yet
            // Filter is a fast and elegant way to make this comparison
            // Looping through each object would be tedious and slow

//
//            var tempString = "\(ename) \(eusername) \(emacaddress) \(ecurrentTitle) \(eskills) \(ecompany) \(eresponsibilities)"
//
//            if let pastEmployer = epastEmployers["company"] as? String {
//
//                tempString += "\(pastEmployer)"
//            }
//            else if let currentResponsibilities = eresponsibilities["responsibilities"] as? String {
//
//                tempString += "\(currentResponsibilities)"
//            }
            
           
        }
    }
    
//    func addEmployee(_employee: Employee) {
//        if let currentSkills = eskills["skills"] as? String {
//
//            _employee.skills.append()
//        }
//    }

    func displayEmployee() {
        
        empName.text = employees[0].name.description
    }
    
    @IBAction func currentEmpChanged(_ sender: UIButton) {
    }
    
    
}

这是我的 Employee.swift 文件的代码:

//
//  Employee.swift
//  BoschBrookeCE02
//
//  Created by Brooke Bosch on 7/3/21.
//

import Foundation

class Employee {
    
    // Stored properties
    let name: String
    let username: String
    let macaddress: String
    let currentTitle: String
    let skills: [String]
    let pastEmployers: [String]!
    let currentCompany: String
    let responsibilities: [String]
    
    // computed properties
    
    
    // Initializers
    init(name: String, username: String, macaddress: String, currentTitle: String, skills: [String], pastEmployers: [String]!, currentCompany: String, responsibilities: [String]) {
        
        self.name = name
        self.username = username
        self.macaddress = macaddress
        self.currentTitle = currentTitle
        self.skills = skills
        self.pastEmployers = pastEmployers
        self.currentCompany = currentCompany
        self.responsibilities = responsibilities
    }
    
    
    
    // Methods
    
}

最后,我的 EmployeeData.json 文件

[{"employeename":"Shawn Cunningham","username":"scunningham0","macaddress":"41-6A-75-B0-2E-73","current_title":"Programmer Analyst IV","skills":["VPython","EES","CD covers","RED MX"],"past_employers":[{"company":"Zboncak-O'Conner","responsibilities":["Extended next generation database"]},{"company":"Friesen, Runolfsson and Kautzer","responsibilities":["Switchable discrete conglomeration","Synergized client-driven project","Universal full-range website","Secured optimal productivity","Balanced multimedia solution"]},{"company":"Zieme-Cronin","responsibilities":["Cloned empowering solution"]}]},
{"employeename":"Martin Wallace","username":"mwallace1","macaddress":"AE-B2-85-08-74-8F","current_title":"Associate Professor","skills":["FBT","Theory","CMMI Level 5","MQL"],"past_employers":[]},
{"employeename":"Roy Young","username":"ryoung2","macaddress":"7C-BD-D4-15-65-ED","current_title":"Mechanical Systems Engineer","skills":["EPA"],"past_employers":[{"company":"Hauck Group","responsibilities":[]},{"company":"DuBuque, Wyman and Kuvalis","responsibilities":[]},{"company":"Hickle and Sons","responsibilities":["Visionary zero defect customer loyalty","Decentralized responsive implementation","Inverse user-facing data-warehouse"]}]},
{"employeename":"Anthony Berry","username":"aberry3","macaddress":"AE-EE-3F-5E-2F-07","current_title":"Help Desk Operator","skills":["KOL Identification","Web Content","JDeveloper","DB2"],"past_employers":[{"company":"Champlin-Emard","responsibilities":["Cross-platform 3rd generation service-desk","Synergized 6th generation paradigm"]}]},
{"employeename":"Jerry Murphy","username":"jmurphy4","macaddress":"0F-BA-ED-D5-95-D5","current_title":"Sales Representative","skills":["Ehcache","FNMA"],"past_employers":[{"company":"Heidenreich Inc","responsibilities":["Digitized encompassing service-desk","Sharable transitional instruction set","Re-engineered tertiary flexibility","Multi-lateral composite moratorium","Multi-tiered methodical orchestration"]}]},
{"employeename":"Gregory Lawrence","username":"glawrence5","macaddress":"E5-BC-80-A4-A4-3E","current_title":"Financial Analyst","skills":["Gutters","Karl Fisher"],"past_employers":[{"company":"Buckridge-Armstrong","responsibilities":["Robust 5th generation core"]},{"company":"Medhurst-Kovacek","responsibilities":["Operative disintermediate middleware","Optional dedicated installation","Multi-tiered foreground artificial intelligence","Automated attitude-oriented algorithm"]},{"company":"Kuhic, Beer and Runolfsson","responsibilities":["Assimilated explicit adapter","Ameliorated maximized benchmark"]}]},
{"employeename":"Linda Myers","username":"lmyers6","macaddress":"BF-9D-78-1C-8E-E1","current_title":"Financial Advisor","skills":["Special Effects","PCI DSS"],"past_employers":[{"company":"Weber-Ernser","responsibilities":[]},{"company":"Homenick, Nicolas and Kassulke","responsibilities":["Right-sized attitude-oriented instruction set","Customizable scalable help-desk","Secured mission-critical intranet","Versatile stable help-desk","Synergized composite initiative"]},{"company":"Zemlak Inc","responsibilities":["Seamless upward-trending circuit","Advanced object-oriented software","Business-focused asymmetric project"]}]},
{"employeename":"Alice Hunter","username":"ahunter7","macaddress":"A9-65-3D-10-01-8C","current_title":"Nurse","skills":["Estate Jewelry","Legal Research","Social Media Blogging"],"past_employers":[{"company":"Abernathy Group","responsibilities":["Business-focused empowering toolset","Object-based systemic application","Triple-buffered demand-driven analyzer","Cross-platform didactic intranet"]}]},
{"employeename":"Lois Elliott","username":"lelliott8","macaddress":"03-93-D1-52-7D-91","current_title":"Research Assistant IV","skills":["DDR2","BCM","Airline Management","IT Infrastructure Management","Helicopters"],"past_employers":[{"company":"Lesch-Kunze","responsibilities":["Ergonomic analyzing contingency","Triple-buffered radical moratorium","Realigned zero tolerance functionalities","Vision-oriented mission-critical access"]}]},
{"employeename":"Sandra Alvarez","username":"salvarez9","macaddress":"C4-BF-22-9C-02-44","current_title":"Paralegal","skills":["DSE Assessments"],"past_employers":[{"company":"Murphy-Zemlak","responsibilities":["Optional transitional intranet","Managed bi-directional functionalities","Synergized uniform toolset"]},{"company":"Howe LLC","responsibilities":["Self-enabling content-based intranet","Enterprise-wide tertiary project"]},{"company":"Dare and Sons","responsibilities":["Decentralized upward-trending capacity","Operative discrete ability","Right-sized bottom-line orchestration","User-centric exuding conglomeration"]}]},
{"employeename":"Diane Russell","username":"drussella","macaddress":"5C-2D-32-7D-01-7F","current_title":"Registered Nurse","skills":["KnockoutJS","Wufoo","IAS 39","Childhood Obesity","Amazon RDS"],"past_employers":[]},
{"employeename":"Amanda Grant","username":"agrantb","macaddress":"FC-B6-7B-B3-77-47","current_title":"Software Test Engineer IV","skills":["AVEVA PDMS"],"past_employers":[{"company":"Miller Group","responsibilities":["Assimilated hybrid migration","Future-proofed regional capacity","Re-contextualized system-worthy migration"]},{"company":"Smitham-Kunze","responsibilities":["Programmable 24/7 firmware","Networked systematic throughput","Streamlined interactive orchestration","Enterprise-wide 24/7 circuit","Organized didactic Graphic Interface"]},{"company":"Harvey Group","responsibilities":["Triple-buffered hybrid strategy","Switchable intangible hierarchy","Synergistic coherent Graphic Interface"]}]},
{"employeename":"Philip Stewart","username":"pstewartc","macaddress":"02-22-FB-BA-F9-DE","current_title":"Paralegal","skills":["WiMAX","Tubing"],"past_employers":[{"company":"Abernathy, Murazik and Gerhold","responsibilities":["Future-proofed object-oriented secured line","Distributed didactic portal","Reactive coherent challenge","Proactive transitional success"]},{"company":"Kassulke and Sons","responsibilities":["Programmable web-enabled open system","Grass-roots bi-directional encryption","Streamlined neutral projection","Diverse client-server protocol"]},{"company":"Wiegand, Powlowski and Flatley","responsibilities":["Operative disintermediate forecast"]}]},
{"employeename":"Jack Johnston","username":"jjohnstond","macaddress":"C4-0E-4D-8C-DE-7D","current_title":"Nurse Practicioner","skills":["BDD","Risk Assessment","KPI Reports"],"past_employers":[]},
{"employeename":"Ralph Bishop","username":"rbishope","macaddress":"D5-0D-1B-D8-97-E2","current_title":"Programmer IV","skills":[],"past_employers":[]},
{"employeename":"Martin Smith","username":"msmithf","macaddress":"B3-A1-20-AC-FA-ED","current_title":"Automation Specialist IV","skills":["QNX","Integrated Circuit Design"],"past_employers":[{"company":"Denesik-Hamill","responsibilities":["Compatible leading edge pricing structure","Realigned maximized help-desk","User-friendly foreground productivity"]}]},
{"employeename":"Laura Lawson","username":"llawsong","macaddress":"21-73-52-CD-50-1C","current_title":"Senior Developer","skills":["International Sales","ODI","TCD"],"past_employers":[{"company":"Brekke-Schmeler","responsibilities":[]}]},
{"employeename":"Lisa Mills","username":"lmillsh","macaddress":"E8-31-0D-D1-C8-22","current_title":"Technical Writer","skills":["Joomla","GNU C","PWS","Aerial Lifts"],"past_employers":[]},
{"employeename":"Louis Perez","username":"lperezi","macaddress":"42-35-3F-2A-A9-52","current_title":"Environmental Specialist","skills":["RPM","Nutritional Counseling","Zendesk"],"past_employers":[{"company":"Rutherford, Okuneva and Steuber","responsibilities":["Devolved attitude-oriented intranet","Stand-alone disintermediate budgetary management","Decentralized value-added function","Multi-channelled dedicated intranet"]},{"company":"DuBuque-Schroeder","responsibilities":["Automated stable circuit","Virtual coherent groupware"]},{"company":"Jast, Rippin and Nicolas","responsibilities":["Multi-layered intangible moratorium","Right-sized web-enabled emulation","Business-focused uniform capacity","Organized eco-centric toolset","Seamless solution-oriented moderator"]}]},
{"employeename":"Bonnie Snyder","username":"bsnyderj","macaddress":"5F-A8-ED-1E-DF-AF","current_title":"Account Coordinator","skills":[],"past_employers":[{"company":"Champlin, Ritchie and Wiegand","responsibilities":["Persevering fresh-thinking focus group","Visionary stable core"]}]}]

标签: jsonswift

解决方案


past_employers的是一个Array<Dictionary>,而不是一个Dictionary

"past_employers":[
{"company":"Zboncak-O'Conner","responsibilities":["Extended next generation database"]},
{"company":"Friesen, Runolfsson and Kautzer","responsibilities":["Switchable discrete conglomeration","Synergized client-driven project","Universal full-range website","Secured optimal productivity","Balanced multimedia solution"]},
{"company":"Zieme-Cronin","responsibilities":["Cloned empowering solution"]}
]

这条线失败了。

let epastEmployers = object["past_employers"] as? [String: Any]

如果您将其更改为

let epastEmployers = object["past_employers"] as? [[String: Any]]

现在它将强制您从ArrayNOT访问所有雇主信息Dictionary。因此,以下所有行都必须在 for 循环内。

// Wrong, `epastEmployers` is an Array
let pcompany = epastEmployers["company"] as? String,
let presponsibilities = epastEmployers["responsibilities"] as? String,
let ecompany = object["company"] as? String,
let eresponsibilities = object["responsibilities"] as? [String]

// Right
for epastEmployer in epastEmployers {
    let ecompany = epastEmployer["company"] as? String
    let eresponsibilities = epastEmployer["responsibilities"] as? [String]
}

推荐阅读