如何使用Swift正确访问自定义类中的JSON响应数据?

时间:2015-04-13 04:52:05

标签: ios json swift

我已经从我的JSON访问了我想要的数据,但我的postTitles数组的行为并不像我期望的那样。我仍然围绕着Swift,并希望在iOS上测试我的Express.js REST API作为客户端。

import Foundation

class Post {

    var className = "Post"

    var postTitles:[String] = []

    class func loadPosts() -> Post {

        let post = Post()

        request(.GET, "http://localhost:8080/posts").responseJSON {
        (_, _, JSON, _) in

            if let json = JSON as? [String : NSArray] {

                if let data = json["data"] {

                    if let postData: AnyObject = data as AnyObject? {

                        for var i = 0; i < postData.count; ++i {

                            if let postTitle = postData[i]["title"] as? String {

                                post.postTitles.append(postTitle)

                                // prints out:
                                // [The After]
                                // [The After, The Kraken]
                                // [The After, The Kraken, The Cream]

                            }

                        }

                    }

                }

            }

        }

        // prints: "Post"
        println(post.className)
        // prints: []
        // Why won't it print [The After, The Kraken, The Cream]?
        println(post.postTitles)

        return post

    }

}

为什么数组是空的?

0 个答案:

没有答案