Search code examples
swiftalamofireswifty-json

My API request code produces a bug I can't debug or understand


I am not sure where to identify the problem in this code

var events = [Events]()

    let URL_GET_DATA = "http://192.168.100.4/PrototypeWebService/api/getevents.php"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        Alamofire.request(URL_GET_DATA).responseJSON{ response in
            if let json = response.result.value {
                print(json)
                let swiftvar = JSON(json).array
                for i in 0..<(swiftvar?.count)! {
                    let jsonObject = swiftvar?[i].object
                    self.events.append(jsonObject as! Events)
                }
                self.EventTable.reloadData()
            }
        }
    } 

I expect it to create an array of objects of type Events but it produces this error :

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x102ca0f4c


Solution

  • First of all you are encouraged to drop SwiftyJSON in favor of Codable.

    The error occurs because a (Swifty)JSON object cannot be cast to a custom struct or class.

    You have to pass the JSON value to an initializer of the custom struct.

    struct Event { // it's highly recommended to name this kind of object in singular form
       let varA : String
       let varB : Int
    
       init(json: JSON) {
          self.varA = json["varA"].string ?? ""
          self.varB = json["varB"].int ?? 0
       }
    }
    

    And please never use index based loops if you actually don't need the index at all. Create an Event instance from the JSON object and append it

    guard let swiftvar = JSON(json).array else { return }
    for item in swiftvar {
         let event = Event(json: item)
         self.events.append(event)
    }
    

    or even simpler

    guard let swiftvar = JSON(json).array else { return }
    self.events = swiftvar.map{ Event(json: $0) }