有人可以解释我那段代码,因为我不能很好地理解。我找到了这段代码,但我无法理解这一行:房间(字典:$0(
var rooms: [Room] = [] // The globale variable
func refresh() {
let request = URLRequest(url: URL(string: "(Config.serverUrl)/rooms")!)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main, completionHandler: { resp, data, err in
guard err == nil else {
return
}
let rooms = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as! [[String: AnyObject]]
self.rooms = rooms.map {
Room(dict: $0) // I can't understand this line
}
self.tableView.reloadData()
})
}
我的房间结构:
struct Room {
var key: String
var title: String
var cat: String!
init(dict: [String: AnyObject]) {
title = dict["title"] as! String
key = dict["key"] as! String
cat = dict["cat"] as! String
}
init(key: String, title: String, cat: String) {
self.key = key
self.title = title
self.cat = cat
}
func toDict() -> [String: AnyObject] {
return [
"title": title as AnyObject,
"key": key as AnyObject,
"cat": cat as AnyObject
]
}
}
如果有人能帮我理解和解释,谢谢
map 函数循环访问集合中的每个项,并对集合中的每个元素应用操作。
这段代码
self.rooms = rooms.map {
Room(dict: $0)
}
是这个的简称。
// `dict` paramater is `$0` in shorter form
self.rooms = rooms.map { (dict : [String: AnyObject]) -> Room in
return Room(dict: dict)
}