gpt4 book ai didi

casting - 如何将 Array 转换为空数组变量?

转载 作者:行者123 更新时间:2023-11-30 10:21:50 25 4
gpt4 key购买 nike

问题:我无法将字符串数组(类型为“AnyObject”)分配给空数组。

步骤:
1. 获取包含字符串和数组的字典。
2. 通过键“photos”从该字典中获取一个数组。
注意: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)' is not convertible to '[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?' does not have a member named 'subscript'

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

必须有一种直接的方法可以从字典中获取嵌入数组,同时转换为相应的转换(没有“anyObject”)。

有什么想法吗?

最佳答案

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

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
}
}

关于casting - 如何将 Array<AnyObject> 转换为空数组变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26045650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com