【发布时间】:2017-05-17 10:28:35
【问题描述】:
我需要一些关于 Swift 3.0 中 NSArray 中的 NSMutableDictionary 的帮助。 该结构是一个字典数组
这是我的代码
class abc{
var myTempArr : NSArray!
}
// I need objC variables as I need to pass them as reference
someMethod(){
myTempArr = [["title":"abc","id":"1"]] // creating a dictionary inside the array
// I have changed the value like this also, but the crash remains
// [["title":"abc","id":"1"] as! NSMutableDictionary]
}
// This method is called in every key stroke in keyboard. Lets say we replace the "title", with the letter in the keyboard it is tapped
func someotherMethod(){
let firstDictionary = myTempArr[0] as! NSMutableDictionary
// Its crashing here!!!!
// Again i need nsmutabledictionary as i need to change the value
// inside the dictionary so that the value inside the main array
// that is myTempArr also changes. I need a pass by reference
// method, hence i choosed NSMutableDictionary instead of swift dictionary
firstDictionary["title"] = "New Title"
// After this line, the original dictionary inside myTempArr
// should change as well. But its crashing in the mentioned line
}
我不想使用类实例,因为我知道它们也是通过引用传递的,但我需要应用 Predicate 来在数组中查找正确的字典,而不是按索引搜索。这也是我无法理解的概念。请帮我解决这个问题。
崩溃说:
无法转换“Swift._SwiftDeferredNSDictionary”类型的值 (0x7facdb71e6c0) 到 'NSMutableDictionary' (0x102bfa350)。
[编辑]
许多人建议选择将字典放入变量中,更改变量然后替换数组中的字典。好吧,我想避免这种方法,因为这与使用基于值的解决方案(Swift Dictionary,其按值传递)相同。我想避免这种情况的原因是,我使用的原始 DS 有大量的字典,并且字典的值经常变化。因此我不认为使用替换字典的方法是正确的。
我也知道 swift 这不好,因为 swift 不是为此而设计的。这种方法在 Objective C 中工作得非常好,因为我们改变变量(提示:变量指针),改变它最初来自的变量。 如果有人可以在 Swift 中提出替代或好的方法,那么请它会很棒。
另外,为了简单起见,我使用了 0 的索引。因为只有 1 个字典。但是在原始 DS 中,我提到了很多字典,因此我使用谓词。这也是我没有使用类的实例(也在 swift 中通过引用传递)的原因,因为当我们通过谓词搜索类的实例时,我不知道它们的行为是否像字典一样。
非常欢迎任何解决方案或替代方案。一如既往地感谢你们为此付出时间,因为我正在努力思考如何采用新方法
【问题讨论】:
-
如果你想要一个
NSMutableDictionary,那么你需要明确地创建一个,但是如果你有一个依赖副作用的函数,那么你可能应该重新考虑你的设计。使用不变性可以提供更健壮的代码。 -
是的,我同意,不变性是要走的路,但我需要处理一个由带有字典数组的数据结构提供支持的表单。现在,每次我通过该表单编辑字典中的任何内容时,我都需要更改字典的确切值。现在这种设计方法不适用于 Swift。但是,如果您能建议任何其他设计或模型,那就太好了。但直到现在我需要解决这个问题
-
使用自定义类而不是字典和 Swift
Array。这也为您提供了参考语义。只要你可以在 Swift 中避免NSMutableArray / -Dictionary,就去做吧! -
会在自定义类工作上做谓词,因为他们在 swift 中工作字典?如您所知,我是 swift 新手,所以请原谅提出这样的问题
-
当然可以,但建议也使用像
filter这样的原生函数。
标签: ios swift3 nsarray nsdictionary