2015年7月7日 星期二

[Swift] Parsing nested Dictionary

I have a network discovery service that will output the following data in debugger:
{
    Device1 =     {
        date = "2015-07-07 08:11:56 +0000";
        name = Device1;
        recent = 0;
        url = "http://192.168.1.10:80";
    };
}

This data is in the form of:
Dictionary(String, Dictionary(String:String,String:String,String:String,String:String))

To extract this nested dictionary in Swift, I will run a for loop over each key. Translated into english would be, for each device in the dictionary. 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
for (key,value) in devices
{
    var deData: ImageTitleCellData = ImageTitleCellData()
    var deDevice: AnyObject? = devices.objectForKey(key)
    var url: NSString = deDevice?.objectForKey("url") as! NSString
    url  = url.stringByReplacingOccurrencesOfString(":80", withString: "") 
    deData.Name = devices.objectForKey(key)?.objectForKey("name") as! String
    deData.Subtitle = url.stringByReplacingOccurrencesOfString("http://", withString: "") 
    deData.ImgSrc = "ic_device.png"
    println("\(deData.Name) -> \(deData.Subtitle)")
}

This will have the following output in console:
Device1 -> 192.168.1.10

沒有留言:

張貼留言