ios - 为什么不能为字典条目分配新值?

标签 ios xcode swift

var dict = ["name": "ryan", "age": 13, "gender": "male"]
//error on the next line
dict["hairColor"] = "brown"

在本教程中,我看到上面的代码片段正在运行,但对我来说不是。错误说:

cannot assisgn to the result of this expression.

最佳答案

我可以在旧版本的 Xcode 中重现您的问题,例如 6.0.1。它在最新版本 6.1.1 中运行良好。您应该更新您的 Xcode。

您还需要import Foundation(或通过import UIKitimport Cocoa 隐式导入,其中任何一个都将包含Foundation) 使代码工作,因为这允许编译器假定您需要 NSObject 的字典,因为您试图将混合类型(整数和字符串)放入字典中。这个完整的示例在 6.1.1 中运行良好:

import Foundation // Or Cocoa, or UIKit

var dict = ["name": "ryan", "age": 13, "gender": "male"]
dict["hairColor"] = "brown"

关于ios - 为什么不能为字典条目分配新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27598233/

相关文章:

ios - XCUITest:在 TableView 中查找 CollectionView 失败

ios - 无法将数据加载到自定义 Collection View 中

ios - 两个完全相同的代码,但其中一个代码有僵尸问题

ios - 子类化 XCTestCase 子类 : Test Navigator does not show all tests

ios - 在 Xcode 中包含 "-ObjC"的原因

ios - 在 Xcode8 上自定义 UISegmentedControl 边框和背景 - Swift 3

ios - 为什么我不能直接设置一些类属性?

ios - 触摸时显示不同的按钮图像

iOS SWIFT - 文件存档 - 参数类型 "[String?]": does not conform to expected type'AnyObject'

ios - 应用商店分发过程中存档验证失败并出现错误