循环思想导致FBRequestConnection Swift

时间:2015-03-23 20:38:07

标签: arrays loops swift dictionary

我已经对eventName进行了硬编码,并将其附加到了eventNameArray,因此我可以将其分配给我的表视图中的UILabel。这很好。

func fetchInfo() {


    FBRequestConnection.startWithGraphPath("FBpage/events?fields=name,is_date_only,cover,description", completionHandler: {(connection: FBRequestConnection!, result: AnyObject!, error: NSError!) ->
    Void in

            var eventData = result["data"] as [NSDictionary]
            var getEvent = eventData[0]
            var eventName = getEvent.objectForKey("name") as String
            self.eventNameArray.append(eventName)

            self.tableView.reloadData()


    }
 as FBRequestHandler)


    }//end of fetchfunc

但实际上eventData中有多个字典(它看起来更像是这样,但一次又一次地重复10个以上的事件)

cover =     {
    "cover_id" = 111;
    id = 11;
    "offset_x" = 0;
    "offset_y" = 0;
    source = "https://scontent.xx.fbcdn.net/hphotos-xfp1/v/t1.0-    9/s720x720/1484689_43320_n.jpg?";
    };
description = "Description for 1st event";
id = 111;
"is_date_only" = 0;
name = "First Event";
"start_time" = "2015-04-11T21:00:00+0800";
}, {
cover =     {
    "cover_id" = 222;
    id = 222;
    "offset_x" = 0;
    "offset_y" = 63;
    source = "https://fbcd-xpa1/t3242_431.png";
};
description = "Description for 2nd event";
id = 22222;
"is_date_only" = 0;
name = "Second Event";
"start_time" = "2015-04-10T21:00:00+0800";
}

我将如何循环,以便我可以获取所有的objectForKey(“name”)并将其附加到我的eventNameArray而不是硬编码。我明白我现在所做的不知道如何重构这一点,所以我可以抓住所有东西

谢谢!

1 个答案:

答案 0 :(得分:0)

循环:

var eventNames: [String] = []

for event in events as [[NSObject:AnyObject]] {
    let eventName = event["name"] as String
    eventNames.append(eventName)
}

或者更像是使用闭包:

let eventNames = (events as [[NSObject:AnyObject]]).map({$0["name"] as? String}) 

请记住,我认为每个事件都有一个名字

如果您想确保产生崩溃,您需要先检查它是否存在值。 循环:

var eventNames: [String] = []

for event in events as [[NSObject:AnyObject]] {
    if let eventName = event["name"] as? String {
        eventNames.append(eventName)
    }
}

闭合:

let eventNames = (events as [[NSObject:AnyObject]]).map({$0["name"] as? String})