简体   繁体   中英

Dictionaries in Array in Swift

I'm new to Swift and I have a problem. I'm trying to create an array of dictionaries in my app from table cells results and make a POST. It must be like this:

{"basket":"[{product_id: 6, quantity: 1}, {product_id: 7, quantity: 1}]"}

So there is a part of my code:

var basketNew: [AnyObject] = []

func tableView(bla-bla){
   var basket = ["product_id":"\(myVal)", "quantity":"\(myVal)"]
   self.basketNew.append(basket)
}

After that I put it into new dictionary:

var params = ["basket": self.basketNew] as Dictionary

And get a result from server:

{"basket":"[{product_id: 6}, {quantity: 1}, {product_id: 7}, {quantity: 1}]"}

What am I doing wrong?

This is my POST request:

var request = HTTPTask()
    request.POST(self.domainNew, parameters: params, success: {(response: HTTPResponse) in
        if let data = response.responseObject as? NSData {
            var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("response: \(strData)")
            var err: NSError?
            var result = 0
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as NSDictionary
println("Very Good")
            }
            }, failure: {(error: NSError, response: HTTPResponse?) in
                println("Very Bad")

        })

I'm using framework SwiftHTTP

Try it this way:

var basketNew: [[String: Int]] = []

func tableView(bla-bla){
    basketNew.append(["product_id": 6, "quantity": 1])
}

var params = ["basket": basketNew]

Update:

操场上的屏幕截图

Update 2:

字典数组

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