字典数组中的可选项

Optionals in Dictionary Arrays

我正在处理一些代码并收到了不正确的输出并一直在尝试解决它,我知道它是一个非常简单的修复(或者至少应该是)可能正确地转换或处理它。但是,我尝试了很多次都没有成功。

这是 Swift Playground

中的代码
import UIKit
import Foundation

//  MARK:- Declarations

//  The varible defintions including the expected unique key values, the associated data and the dictionary which will be returned
var arrayOfUniqueFieldNames = ["value1", "value2", "value3"]
var dictionaryOfKeyPairedData : [Int: [String]] = [
    0: ["value1", "a"],
    1: ["value2", "b"],
    2: ["value3", "c"],
    3: ["value1", "x"],
    4: ["value2", "y"],
    5: ["value3", "z"]]
var dictionaryOfDatasets = [String: Any]()

// MARK:- Code Body

//  Iterates through the dictionaryOfKeyPairedData assigning each key if it doesn't exist to the array to print and the value to the existing key, each key has mutliple values stored as an array
for counterOne in 0...dictionaryOfKeyPairedData.count-1{
    
    //  gets the current key value from the dictionary as a String
    let currentKeyValue = returnKeyofDictionaryArray(theDictionaryInQuestion: dictionaryOfKeyPairedData, indexToLookUp: counterOne, value: 0)
    //  gets the current value from the dictionary as a String as it associates with the current key
    let currentValuePair = returnKeyofDictionaryArray(theDictionaryInQuestion: dictionaryOfKeyPairedData, indexToLookUp: counterOne, value: 1)
    //  Fetches the array from the dictionary so it can be manipulated
    var existingItems = Array(arrayLiteral: dictionaryOfDatasets[currentKeyValue]) //Where I believe the Optional is not handled correctly
    //  If the key doesn't exist it saves the value as the key to the key, if it does exist it saves the value to the value as a value
    if existingItems[0] == nil{
        existingItems = [currentValuePair] //Where I believe the extranious brackets are getting added
    }else{
        existingItems.append(currentValuePair)
    }
    //  resaves the manipulated array alongside the existing key
    dictionaryOfDatasets[currentKeyValue] = existingItems
}

//  prints the data - OUTPUT
print(dictionaryOfDatasets)


//  MARK:- Functions
//  Returns the key for the value for the prescribed array
func returnKeyofDictionaryArray(theDictionaryInQuestion: [Int: [String]], indexToLookUp: Int, value: Int) -> String{
    return theDictionaryInQuestion[indexToLookUp]![value]
}

预期输出为

["value2": ["b", "y"], "value1": ["a", "x"], "value3": ["c","z"]]

["value1": ["a", "x"], "value2": ["b", "y"], "value3": ["c","z"]]

实际输出为

["value1": [Optional([Optional("a")]), Optional("x")], "value2": [Optional([Optional("b")]), Optional("y")], "value3": [Optional([Optional("c")]), Optional("z")]]

您正在使用 Any 作为输出字典值的类型,而它可以只是 String 的数组。使用 Array(arrayLiteral: dictionaryOfDatasets[currentKeyValue]) 也无济于事。

你可以通过迭代原始字典并将值直接存储到新字典中来获得你想要的结果,没有像returnKeyofDictionaryArray这样的支持函数。

以下是实现此目标的方法:

        //  The variable defintions including the expected unique key values, the associated data and the dictionary which will be returned
        var arrayOfUniqueFieldNames = ["value1", "value2", "value3"]
        var dictionaryOfKeyPairedData : [Int: [String]] = [
            0: ["value1", "a"],
            1: ["value2", "b"],
            2: ["value3", "c"],
            3: ["value1", "x"],
            4: ["value2", "y"],
            5: ["value3", "z"]]
        
        // This is a dictionary of String to String-arrays
        var dictionaryOfDatasets = [String: [String]]()

        // MARK:- Code Body
        
        // Just iterate through the values of the dictionary, given that
        // you are not interested in the Int keys
        dictionaryOfKeyPairedData.values.forEach {
            if dictionaryOfDatasets[[=10=][0]] == nil {
                dictionaryOfDatasets[[=10=][0]] = [[=10=][1]]
            } else {
                dictionaryOfDatasets[[=10=][0]]?.append([=10=][1])
            }
        }
        
        // Sorting, if you need:
        // Here is where you sort the arrays inside each value of the dictionary
        dictionaryOfDatasets.keys.forEach {
            dictionaryOfDatasets[[=10=]] = dictionaryOfDatasets[[=10=]]?.sorted(by: { [=10=] <  })
        }

        //  prints the data - OUTPUT
        print(dictionaryOfDatasets)   // ["value3": ["c", "z"], "value2": ["b", "y"], "value1": ["a", "x"]]

你,首先你需要把DictioanryAny改成String然后你可以用更优雅的方式达到预期的效果

var arrayOfUniqueFieldNames = ["value1", "value2", "value3"]
var dictionaryOfKeyPairedData : [Int: [String]] = [
    0: ["value1", "a"],
    1: ["value2", "b"],
    2: ["value3", "c"],
    3: ["value1", "x"],
    4: ["value2", "y"],
    5: ["value3", "z"]]
var dictionaryOfDatasets = [String: [String]]()

arrayOfUniqueFieldNames.forEach{
    let key = [=10=]
    dictionaryOfKeyPairedData.filter({[=10=].value.first == key}).forEach{
        if dictionaryOfDatasets[key] != nil {
            var val = dictionaryOfDatasets[key]
            val?.append([=10=].value.last ?? "")
            dictionaryOfDatasets[key] = val

        }else{
            dictionaryOfDatasets[key] = [[=10=].value.last ?? ""]

        }
    }
}
print(dictionaryOfDatasets)

OUTPUT:

["value1": ["a", "x"], "value3": ["z", "c"], "value2": ["y", "b"]]