0
votes

in Swift 1.2

https://gist.github.com/anonymous/a167148a8a6d169292ff

in Swift 2.0 (error) , so I change my code as follows.

let url = NSURL(string:"http://dl-8.one2up.com/onetwo/content/2015/6/15/9c3b51249fbbe20ca9d841401e276d97.php")
    let allContactsData = NSData(contentsOfURL:url!)

    do{
        var allContacts : AnyObject! = try NSJSONSerialization.JSONObjectWithData(allContactsData!, options: NSJSONReadingOptions())
    }catch{
    print(error)
    }

    if let json = allContacts as? Array<AnyObject>  {
    print(json)


        for index in 0...json.count-1 {

            let contact : AnyObject? = json[index]

            let collection = contact! as! Dictionary<String, AnyObject>

            let name : AnyObject? = collection["AnimeName"]
            let cont : AnyObject? = collection["Episodes"]

            names.append(name as! String)
            episodes.append(cont as! String)
        }

    }
    print(names)
    print(episodes)

But that doesn't work.

if let json = allContacts as? Array< AnyObject >

error : Use of unresolved identifier 'allContacts'

2
You should pull your code in from the gist, so that we don't have to open multiple tabs to understand your question. :)Bloodyaugust
I'm Sorry @BloodyaugustShado

2 Answers

2
votes

Your allContacts variable is created in the do block, therefore its scope is limited to the do block, and cannot be accessed outside of that block. If you want it to be accessible outside the block, declare it outside of the block, but then continue to assign it inside the block. IE:

let allContactsData = NSData(contentsOfURL:url!)
var allContacts:AnyObject
do{
   allContacts = try NSJSONSerialization.JSONObjectWithData(allContactsData!, options: NSJSONReadingOptions())
}catch{
print(error)
}
0
votes
do{
var allContacts = try NSJSONSerialization.JSONObjectWithData(allContactsData!, options: NSJSONReadingOptions()) as! [Dictionary<String, AnyObject>]
for contact in allContacts {
let name : AnyObject? = contact["AnimeName"]
let cont : AnyObject? = contact["Episodes"]

names.append(name as! String)
episodes.append(cont as! String)
}
}catch{
print(error)
}