Related question: General completion handler in Swift
In the Swift application I am writing, I load JSON and I want to convert it to model objects. Right now, I'm doing it like this:
func convertJSONData<T: Entity>(jsonData: NSData?, jsonKey: JSONKey, _: T.Type) -> [T]? { var entities = [T]() if let data = jsonData { // Left out error checking for brevity var json = JSON(data: data, options: nil, error: nil) var entitiesJSON = json[jsonKey.rawValue] for (index: String, subJson: JSON) in entitiesJSON { // Error: EXC_BAD_ACCESS(code=EXC_I386_GPFLT) let entity = T(json: subJson) entities.append(entity) } } return entities }
Each entity corresponding to Entity implements init(json: JSON) . JSON is a type defined in the SwiftyJSON library. This is also the reason the listing looks a bit odd.
I call convertJSONData() in this method:
public func performJSONRequest<T where T: Entity>(jsonRequest: JSONRequest<T>) { var urlString = ... Alamofire.request(.GET, urlString, parameters: nil, encoding: .JSON).response { (request, response, data, error) -> Void in var books = self.convertJSONData(data as? NSData, jsonKey: jsonRequest.jsonKey, T.self) jsonRequest.completionHandler(books, error) } }
I get an EXC_BAD_ACCESS(code=EXC_I386_GPFLT) runtime EXC_BAD_ACCESS(code=EXC_I386_GPFLT) causing T(json: subJSON) . There are no warnings or compiler errors. Although I left error checking in the above code, there is error checking in the actual code, and error is zero.
I am not sure if this is a compiler error or my mistake, and any help is that it is very valuable.