如何将Array <anyobject>转换为空数组变量?</anyobject>

时间:2014-09-25 18:32:43

标签: casting swift

问题:我无法将字符串数组(键入'AnyObject')分配给空数组。

步骤:
1.获取包含字符串和字典的字典。阵列。
2.通过键“照片”从这本词典中获取一个数组。
   注意:Xcode的警告表明我给出了显式类型'AnyObject'。
3.创建一个空数组。
4.尝试分配(失败)。

let responseDictionary = responseDict as [String : AnyObject]
let ricPhotos:AnyObject = responseDictionary["photos"]!              
var thePhotos:Array<AnyObject>?              
thePhotos = ricPhotos  <--- fails

编译错误:

...'AnyObject' is not convertible to 'Array<AnyObject>'

问题:如何将'ricPhotos'分配给空数组'thePhotos',最好将'AnyObject'转换为'String'?

<小时/> 的修订

let responseDictionary = responseDict as [String : AnyObject]
var anyObject: AnyObject? = responseDictionary["photos"]

好的,'anyObject'似乎是一个字典,里面是'photo',它是一个数组;如数据所示。 这是一些数据(anyObject):

{
    page = 1;
    pages = 1334;
    perpage = 100;
    photo =     (
                {
            farm = 3;
            "height_m" = 336;
            "height_s" = 161;
            "height_sq" = 75;
            "height_t" = 67;
            id = 15166756998;
            isfamily = 0;
            isfriend = 0;
            ispublic = 1;
            owner = "127012961@N08";
            secret = 053032f300;
            server = 2941;
            title = "You @NYPL";
            "url_m" = "https://farm3.staticflickr.com/2941/15166756998_053032f300.jpg";
            "url_s" = "https://farm3.staticflickr.com/2941/15166756998_053032f300_m.jpg";
            "url_sq" = "https://farm3.staticflickr.com/2941/15166756998_053032f300_s.jpg";
            "url_t" = "https://farm3.staticflickr.com/2941/15166756998_053032f300_t.jpg";
            "width_m" = 500;
            "width_s" = 240;
            "width_sq" = 75;
            "width_t" = 100;
        },
        ...etc.

我想抓住'照片'数组。但是我不能将'anyObject'转发为'Dictionary',以便我可以下标它。我试过了:

var anyObject:Dictionary = responseDictionary["photos"]

但我得到了:

  

'(String,AnyObject)'不能转换为'[String:AnyObject]'

所以我坚持:

var anyObject: AnyObject? = responseDictionary["photos"]

所以使用anyObject,我试图访问“照片”:

let RicPhotos = anyObject["Photo"] as [String : AnyObject]

......我也试过了:

let RicPhotos = anyObject["Photo"] as Array<Dictionary<String,String>>

但我得到了:

  

“AnyObject?没有名为'subscript'的成员

我可以看到数据,但我无法提取到一个空变量。
我试图向下转换为特定类型(Dictionary),但编译器拒绝。

必须是一种从字典中获取嵌入数组同时转换为其各自的演员阵容(没有'anyObject')的直接方式。

任何想法?

1 个答案:

答案 0 :(得分:1)

编辑我的答案以适应您的编辑...

let responseDictionary = [:] as [String : AnyObject]
var photosDic: AnyObject? = responseDictionary["photos"]
if let photosDic = photosDic as? Dictionary<String, AnyObject> {
    var photosArray: AnyObject? = photosDic["photo"]
    if let photosArray = photosArray as? Array<Dictionary<String, AnyObject>> {
        //There you go
    }
}