将数组放入swift3节

时间:2017-08-19 21:57:16

标签: ios arrays swift

在论坛上得到答案后,我修改了我的代码,这是我的问题:

1)在viewDidLoad()之后,我创建了一个数组来提供显示

var sections = [
    Section(genre: " Event du mois",
            movies: ["The Incredibles", "The Incredibles"],
            expanded: false),
    Section(genre: " Top Event",
            movies: ["Guardians of the Galaxy", "The Flash", "The Avengers", "The Dark Knight"],
            expanded: false),
    Section(genre: " Event Fribourg",
            movies: ["The Walking Dead", "Insidious", "Conjuring"],
            expanded: false)
]

2)我想用我的数据库中的数组替换这个数组。

var sections = [Section]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let myUrl = Constants.Path.APIview

        var request = URLRequest(url: URL(string: myUrl)!)
        request.httpMethod = "POST"
        let postString = ""
        request.httpBody = postString.data(using: .utf8)

      let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

            //Convert response sent from a server side script to a NSDictionary object:
            do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                if let parseJSON = json
                {
                    let eventMois = parseJSON["event"] as? NSArray

                    sections = eventMois

                }

            }catch {
                print(error)
        }

            }
        task.resume()

        }

我发现此错误消息:无法为NSarray分配值以输入[Section] 我可以将数组放入一个部分吗?

1 个答案:

答案 0 :(得分:1)

NSArray的内容也必须是Section类型。我猜eventMois是JSON类型的,所以你想把这个json转换成Section个对象的数组,然后编译器不会抱怨。