使用字符串迭代字典,在Swift中使用任何对

时间:2018-04-02 15:03:01

标签: swift list dictionary enumeration

我编写了这个函数,它从文本文件中读取值并将它们存储在字典中。字典的格式为:[String : Any]。字典中的每个键都与一个Zipped列表相关联。如果值symbol作为字典中的键存在,则该函数返回与该键关联的值。该函数正常工作,并能够返回字典中该关联键的值。但是由于错误type 'Any' does not conform to protocol 'Sequence',我无法迭代返回的列表。我已经检查了函数中返回值的类型,该函数显示为Zip2Sequence<Array<String>, Array<Any>>。使用dump在控制台上显示变量也会显示返回的值是列表类型。知道为什么我不能迭代返回的列表吗?

变量_element_data定义为; var _element_data : Dictionary<String, Any>

func lookup_element_data( symbol : String, copy:Bool = true) -> Any{

        if _element_data.count == 0{

            let Keys : [String] = ["Symbol", "Name", "Z", "Mass", "r_cov", "e_affinity", "p_eig", "s_eig", "Abundance", "el_neg", "ion_pot"];

            //Gets all the data from the file element_data.txt as a 2D string array
            //_get_data_rows works correclty
            let elementDataFile = _get_data_rows(filename: "element_data");

            for items in elementDataFile{

                //Take each item in the list and:
                //filter the items out into Optional(number) and nil
                var convertedNumerals = items.map({ float_or_Nil(x: $0) });
                var tempList : [String] = Array(items[0...1]); //store each string in an array of type Any
                let tempListBack : [Float?] = Array(convertedNumerals[2...]);

                var convertedList : [Any] = tempList;
                convertedList.append(tempListBack); //Combining the two lists together

                //Zipping keys with items together
                let zipped = zip(Keys, convertedList);

                //Asign value with key element data converted to String
                //Each key is assoicated with a list of pairs of each element
                _element_data[tempList[0]] = zipped;
             }
        }

        //If the item is a key in the dictionary
        if _element_data[symbol] != nil{

            //Return the value assoicated with this specific symbol
            return _element_data[symbol]!;
        }else{
            return [];
        }

    }

0 个答案:

没有答案