Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift dictionary bug?

So I started a project in Swift, and I've come to this problem:

this code works:

var dictionary = ["a":"valueOfA","b":"valueOfB","c":"valueOfC"]
println(dictionary)
dictionary["c"] = "newValOfC"
println(dictionary)

and this doesn't:

var dictionary = [:]
dictionary = ["a":"valueOfA","b":"valueOfB","c":"valueOfC"]
println(dictionary)
dictionary["c"] = "newValOfC"
println(dictionary)

Gives an error:

Playground execution failed: error: <REPL>:35:17: error: cannot assign to the result of this expression
dictionary["c"] = "newValC"
~~~~~~~~~~~~~~~ ^

Notice that this is not a constant value

So why doesn't the line

dictionary = ["a":"valueOfA","b":"valueOfB","c":"valueOfC"]

give an error?

like image 574
vrwim Avatar asked Jun 03 '14 19:06

vrwim


2 Answers

Since the context does not provide enough information to infer the type, you'll need to explicitly name it as a dictionary, otherwise swift assumes it is an NSDictionary (I'm not clear on why though. I assume for better obj-c compatibility):

The following code all works:

// Playground
import UIKit

var str:NSString = "Hello, playground"

var d0 = [:]
var d1: Dictionary = [:]

d0.setValue(UIWebView(), forKey: "asdf")

d1["asdf"] = 1
d1["qwer"] = "qwer"
like image 108
Jiaaro Avatar answered Nov 16 '22 03:11

Jiaaro


Okay, I found it, the problem is that by initializing an empty dictionary, the type inference gets a little crazy.

You'll need this code:

var dictionary = Dictionary<String, String>()

instead of

var dictionary = [:]

but that still does not explain why the line

dictionary = ["a":"valueOfA","b":"valueOfB","c":"valueOfC"]

does not give an error

like image 22
vrwim Avatar answered Nov 16 '22 03:11

vrwim