kellanburket
kellanburket

Reputation: 12843

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. sections is an array of custom Section objects and its method getValue always returns a 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>. 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.

Upvotes: 0

Views: 376

Answers (1)

tng
tng

Reputation: 4346

The general problem is that a "cast expression" does not yield an "l-value" and therefore cannot be assigned to. 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".

Upvotes: 1

Related Questions