3

When creating a dictionary in swift with array of strings as value as follows:

lazy var info : Dictionary = {

    var dictionary = [String: [String]]()
    dictionary["Key1"] = ["A", "B", "C"]
    dictionary["Key2"] = ["D", "E", "F"]

    return dictionary  
}()

Cannot assign to immutable expression of type 'Value?'

Any ideas whats wrong here?

2
  • This error message usually comes up, when declaring dictionary with let. But you have done it right in this snippet. Are you sure, you've done it the same way in your real code? Commented Nov 27, 2015 at 11:42
  • 1
    The problem was that you can't use Dictionary with a lazy var - had to change Dictionary to NSDictionary and all was fine. Commented Nov 27, 2015 at 11:47

2 Answers 2

6

I've seen your own answer, which works, but there's a better way: use a Swift dictionary by declaring its proper type, in your case [String: [String]]:

lazy var info : [String: [String]] = {

    var dictionary = [String: [String]]()
    dictionary["Key1"] = ["A", "B", "C"]
    dictionary["Key2"] = ["D", "E", "F"]

    return dictionary
}()
Sign up to request clarification or add additional context in comments.

2 Comments

Was just going to comment this too. @XCodeWarrier It is even better to keep all type declarations separate from initial values var dictionary : [String: [String]] = [:]
Perfect answer! Let's keep moving forward with Swift instead of resorting to the old Objective-C classes (like NSDictionary).
0

Change

lazy var info : Dictionary = {

    var dictionary = [String: [String]]()
    dictionary["Key1"] = ["A", "B", "C"]
    dictionary["Key2"] = ["D", "E", "F"]

    return dictionary  
}()

to

lazy var info : NSDictionary = {

    var dictionary = [String: [String]]()
    dictionary["Key1"] = ["A", "B", "C"]
    dictionary["Key2"] = ["D", "E", "F"]

    return dictionary  
}()

and all is good :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.