Swift字典错误? [英] Swift dictionary bug?
本文介绍了Swift字典错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在Swift开始了一个项目,我来了这个问题:
So I started a project in Swift, and I've come to this problem:
这段代码的工作原理:
var dictionary = ["a":"valueOfA","b":"valueOfB","c":"valueOfC"]
println(dictionary)
dictionary["c"] = "newValOfC"
println(dictionary)
这不是:
var dictionary = [:]
dictionary = ["a":"valueOfA","b":"valueOfB","c":"valueOfC"]
println(dictionary)
dictionary["c"] = "newValOfC"
println(dictionary)
发送错误:
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
所以为什么不行
dictionary = ["a":"valueOfA","b":"valueOfB","c":"valueOfC"]
给出错误?
推荐答案
由于上下文没有提供足够的信息来推断该类型,您需要明确地将其命名为字典,否则swift假定它是一个 NSDictionary
(我不清楚为什么。我假设更好的对象兼容性):
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"
这篇关于Swift字典错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文