简体   繁体   English

字符串不可转换为DictionaryIndex <String, AnyObject>

[英]String not convertible to DictionaryIndex<String, AnyObject>

I have a function that loops through an array that contains either Strings or Dictionaries and sets values for a new Dictionary of type [String:AnyObject] , using values from the original array as keys. 我有一个函数,该函数遍历包含字符串或字典的数组,并使用原始数组中的值作为键为[String:AnyObject]类型的新字典设置值。 sections is an array of custom Section objects and its method getValue always returns a String . sections是自定义Section对象的数组,其方法getValue始终返回String

func getSectionVariables() -> [String:AnyObject] {
    var variables = [String:AnyObject]()

    for section in sections {
        if let name = section.name as? String {
            variables[name] = section.getValue()
        } else if let name = section.name as? [String:String] {
            for (k, v) in name {
                if variables[k] == nil {
                    variables[k] = [String:String]()
                }

                if var dict = variables[k] as? [String:String] {
                    dict[v] = section.getValue() //This works, but of course copies variables by value and doesn't set variables[k] 
                }

                (variables[k] as? [String:String])![v] = section.getValue() //Can't get this line to compile
            }
        }
    }

    return variables
}

If I try to cast variables[k] as a [String:String] , the compiler insists that String is not convertible to DictionaryIndex<String, AnyObject> . 如果我尝试将variables[k][String:String] ,则编译器坚持认为String is not convertible to DictionaryIndex<String, AnyObject> I'm not sure why downcasting isn't working and why the compiler thinks I'm trying to use the alternate dictionary subscript syntax. 我不确定为什么向下转换不起作用,以及为什么编译器认为我正在尝试使用备用字典下标语法。

Note that this project is in Swift 1.1. 请注意,该项目在Swift 1.1中。

The general problem is that a "cast expression" does not yield an "l-value" and therefore cannot be assigned to. 普遍的问题是“ cast表达式”不会产生“ l值”,因此无法分配给它。 For example, consider the following simplified version of the code: 例如,考虑下面的简化版本的代码:

var x = "initial"
var y : AnyObject? = x
(y as? String) = "change"

You will get an error on the last line, because you cannot assign to a "cast expression". 您将在最后一行收到错误,因为您无法分配给“ cast expression”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM