如何将数组添加到字典?

时间:2019-04-18 18:37:38

标签: arrays swift dictionary

我正在尝试将数组添加到字典中,但出现此错误:

  

无法将类型[[[String:String]]]的值转换为预期的字典值类型'Array

这是我的实现方式:

class PdfUpload(APIView):

parser_classes = (MultiPartParser, FormParser,)

def get(self, request):
    return Response([PdfSerializer(file).data for file in Pdf.objects.all()])

def post(self,request):
    payload=(request.data,request.FILES)
    print("Hello")
    print(payload)
    serializer=PdfSerializer(data=payload)

    if serializer.is_valid():
        serializer.save()
        return Response("File Saved in Backend",status=status.HTTP_201_CREATED)
    return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

在此行let dicContent:[String: String] = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"] var myArray:Array = [[String: String]]() myArray.append(dicContent) let mainDict:[String:Array] = ["MainDictionary": myArray] 上出现错误

你们中的任何人可能都知道为什么我会收到此错误或解决方法?

3 个答案:

答案 0 :(得分:2)

请勿使用Array关键字来定义字典类型。尝试按照以下步骤解决您的问题:

let dicContent: [String: String] = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
var myArray = [[String: String]]()
myArray.append(dicContent)
let mainDict: [String: [[String: String]]] = ["MainDictionary": myArray]

在这种情况下,变量的类型可以隐式定义,因此您的代码可以简化为以下形式:

let dicContent = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
let mainDict = ["MainDictionary": [dicContent]]

答案 1 :(得分:2)

错误提示,您已将mainDict声明为

let mainDict:[String:Array] 

,但未指定Array的内容。您可以尝试以下方法之一来解决此问题。

尝试:

let dicContent:[String: String] = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
var myArray = [[String: String]]()
myArray.append(dicContent)
let mainDict:[String:[[String: String]]] = ["MainDictionary": myArray]

或者如果您想使用Array关键字,可以按照以下步骤操作:

let dicContent:[String: String] = ["Alabama": "Montgomery", "Alaska":"Juneau","Arizona":"Phoenix"]
var myArray = Array<[String: String]>()
myArray.append(dicContent)
let mainDict:[String:Array<[String:String]>] = ["MainDictionary": myArray]

或者简单地

let mainDict = ["MainDictionary": myArray]

使用数组关键字时,需要指定数组将在<...>

中保留的对象类型。

答案 2 :(得分:1)

let dicContent:[String: String] = ["Alabama": "Montgomery", 
"Alaska":"Juneau","Arizona":"Phoenix"]
var myArray  = [[String: String]]()
myArray.append(dicContent)
let mainDict:[String:Any] = ["MainDictionary": myArray]
let getArrayBack = mainDict["MainDictionary"] as! [[String:String]]