I'm new in swift language, newbie question but I have to ask cause my mind is little bit confused about dictionary and array usage here, I got a json like this;
{
"MainPageLast": [
{},
{}..
],
"MainPageSport": [
{},
{}..
],
"MainPageEco": [
{},
{}..
],
"MainPagePol": [
{},
{}..
]
}
I made base class which includes all of these arrays as dictionary like this;
public class func modelsFromDictionaryArray(array:NSArray) -> [Json4Swift_Base]
{
var models:[Json4Swift_Base] = []
for item in array
{
models.append(Json4Swift_Base(dictionary: item as! NSDictionary)!)
}
return models
}
required public init?(dictionary: NSDictionary) {
if (dictionary["MainPageLast"] != nil) { mainPageLast = MainPageLast.modelsFromDictionaryArray(dictionary["MainPageLast"] as! NSArray) }
if (dictionary["MainPageSport"] != nil) { mainPageSport = MainPageSport.modelsFromDictionaryArray(dictionary["MainPageSport"] as! NSArray) }
if (dictionary["MainPageEco"] != nil) { mainPageEco = MainPageEco.modelsFromDictionaryArray(dictionary["MainPageEco"] as! NSArray) }
if (dictionary["MainPagePol"] != nil) { mainPagePol = MainPagePol.modelsFromDictionaryArray(dictionary["MainPagePol"] as! NSArray) }
}
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
return dictionary
}
And I try to get data and try to parse and want to see the returning data in debug screen;
func loadHeadline(completion : ((AnyObject) -> Void)!) {
let urlString = "http://myapiurl."
let session = NSURLSession.sharedSession()
let newsUrl = NSURL(string: urlString)
let task = session.dataTaskWithURL(newsUrl!, completionHandler: {
(data, response, error) -> Void in
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! Dictionary<String, AnyObject>
var models:[Json4Swift_Base] = []
for item in jsonData
{
models.append(Json4Swift_Base(dictionary: item as NSDictionary)!)
}
} catch let error as NSError{
print("Failed to load: \(error.localizedDescription)")
}
})
task.resume()
}
I know I need to reach each [0], [1]... items one by one in Json4Swift_Base class but I really could not figure how to.
This Exception throws when I try to
models.append
exc_bad_instruction (code=exc_i386_invop subcode=0x0)
Now, which way should I follow or what to do to get and put all data in one.
Thanks in advice..
ArrayandDictionarywhich suit the strong type system of Swift much more than the Foundation equivalents.