Swift不能附加到下标?
我似乎无法在下标上使用.append() 例如,以下是阵列:Swift不能附加到下标?,swift,Swift,我似乎无法在下标上使用.append() 例如,以下是阵列: var arrayTest = [ "test": 8, "test2": 4, "anotherarry": [ "test4": 9 ] ] 我能够做到这一点: arrayTest.append(["test3": 3]) 但是我不能附加到arrayTest中的数组。这就是我正在尝试的: arrayTest["anotherarray"].append(["finaltest": 2]) 首先注意:变
var arrayTest = [
"test": 8,
"test2": 4,
"anotherarry": [
"test4": 9
]
]
我能够做到这一点:
arrayTest.append(["test3": 3])
但是我不能附加到arrayTest中的数组。这就是我正在尝试的:
arrayTest["anotherarray"].append(["finaltest": 2])
首先注意:变量
arrayTest
是[String:NSObject]
类型的字典,而不是数组。类似地,键另一个数组的值也是字典
第二个注意事项:您正在设置keyanotherarry
并检索keyanotherarray
,在本例中该数组为nil
我也不确定如何在arrayTest
上调用append()
,因为它是一个字典,没有那种方法
但是,您尝试执行的关键问题是,字典和数组是值类型,在传递时会被复制,而不是被引用。当您下标arrayTest
以获取另一个数组时,您得到的是值的副本,而不是字典中的值引用
如果要直接在数组或字典中修改某个内容(而不是替换它),则该内容必须是引用类型(类)。下面是一个如何完成代码的示例:
var arrayTest = [
"test": 8,
"test2": 4,
"anotherarray": ([
"test4": 9
] as NSMutableDictionary)
]
(arrayTest["anotherarray"] as? NSMutableDictionary)?["test5"] = 10
请注意,此代码强制“anotherarray”显式为NSMutableDictionary
(Objective-C中的类类型),而不是默认为Swift字典(值类型)。这使得从字典之外修改它成为可能,因为它现在作为引用传递,而不是复制
进一步说明:
正如在评论中指出的,使用NSMutableDictionary不是我个人推荐的,也不是一个纯粹的Swift解决方案,它只是以最少的代码更改获得一个工作示例的方法
您的其他选项包括将另一个数组
值完全替换为修改后的副本,而不是尝试直接为其下标,或者如果能够链接下标对您很重要,您可以在Swift字典周围创建一个类包装器,如下所示:
class DictionaryReference<Key:Hashable, Value> : DictionaryLiteralConvertible, CustomStringConvertible {
private var dictionary = [Key : Value]()
var description: String {
return String(dictionary)
}
subscript (key:Key) -> Value? {
get {
return dictionary[key]
}
set {
dictionary[key] = newValue
}
}
required init(dictionaryLiteral elements: (Key, Value)...) {
for (key, value) in elements {
dictionary[key] = value
}
}
}
class DictionaryReference:DictionaryTerralConvertible,CustomStringConvertible{
私有变量字典=[Key:Value]()
变量说明:字符串{
返回字符串(字典)
}
下标(键:键)->值{
得到{
返回字典[键]
}
设置{
字典[键]=新值
}
}
必需的初始化(dictionaryLiteral元素:(键、值)…){
对于元素中的(键、值){
字典[键]=值
}
}
}
然后您将使用与NSMutableDictionary示例类似的方法:
var arrayTest = [
"test": 8,
"test2": 4,
"anotherarray": ([
"test4": 9
] as DictionaryReference<String, Int>)
]
(arrayTest["anotherarray"] as? DictionaryReference<String, Int>)?["test5"] = 10
var arrayTest=[
“测试”:8,
“测试2”:4,
“另一个数组”:([
“测试4”:9
]作为字典参考)
]
(arrayTest[“另一个数组”]作为字典引用)?[“test5”]=10
例如,以下是阵列:
var arrayTest = [
"test": 8,
"test2": 4,
"anotherarry": [
"test4": 9
]
]
不,arrayTest
不是数组。这是一本字典
我能做到这一点
不,你不是。在字典中没有这样的append
方法
问题
看来你有一本这样的字典
var dict: [String:Any] = [
"test": 8,
"test2": 4,
"anotherdict": ["test4": 9]
]
您想要更改密钥另一个dict
(是,我重命名了您的密钥)中的数组,以便添加以下密钥/值对
"finaltest": 2
这是密码
if var anotherdict = dict["anotherdict"] as? [String:Int] {
anotherdict["finaltest"] = 2
dict["anotherdict"] = anotherdict
}
结果
[
"test2": 4,
"test": 8,
"anotherdict": ["test4": 9, "finaltest": 2]
]
我不建议在Swift中使用NSObject
和NSMutableDictionary
类。它们属于Objective-C,在Swift中工作只是为了向后兼容。当然,它们并不代表做事的快捷方式。@appzyorlife是的,我同意,我不推荐它,但这可以说是将海报现有代码转换为工作示例的最短途径。我会在我的答案后面加一条注释。