简体   繁体   中英

AnyObject to string in swift

I am stuck on this code! I want to remove the optionals what is the best way to do that? I tried to change the AnyObject in to NSString but I don't know how.

What is the best way to do this?

And my second question is how do I store this in the core data? Is there a cool framework for this?

Alamofire.request(.GET, urlDb)
        .responseJSON { (request, response, json, error) in
            println(error)
            //println(json)

            if let contactGroups : AnyObject! = json{
                //println("Contact groepen")
                var contactGroups = contactGroups["contact_groups"] as NSArray

                for cG in contactGroups {
                    println(cG["group_id"]!)
                    //println(cG["contact_id"]!)
                }
            }

            if let contacts : AnyObject = json{
                //println(contacts["contacts"])
                println("Contacten")
                var contacts = contacts["contacts"] as NSArray

                for c in contacts{
                    println(c["id"])
                    println(c["name"])
                }
            }
        }    

This is the console log

 nil
 Optional(1)
 Optional(2)
 Contacten
 Optional(1)
 Optional(Dirk Sierd de Vries)

I hope you guys can help me with my school project :D

Modify for loop like below:

for c in contacts {
    println(c["id"]  as NSString)
    println(c["name"] as NSString)
}

Explanation:

In Swift you have to specify object to specific type. If you not than it will by default shows Optional keyword. Here your dictionary key values are directly printed on log and you have not specified that which type of value stored in dictionary.

About Saving in Core Data:

No there isn't any cool framework which can save data into core data. You need to do it your self. Below link is best to follow to start learning this.

Swift + Core data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM