问题描述
我正在尝试使用 NSUserDefaults 保存一个数组,然后加载该数组,但出现错误无法推断通用参数的参数".有什么我做错了吗?似乎没有人迅速遇到这个问题,所以我找不到任何解决方案.
I'm trying to save an array with NSUserDefaults and then load the array, but I get the error "argument for generic parameter could not be inferred." Is there anything I am doing wrong? No one seems to be having this problem in swift, so I can't find any solutions.
IBAction func loadData(sender: AnyObject) {
if let testCompositeArray = defaults.objectForKey("testScoreSATArray") as? Array {
self.showDataLabel.text = defaults.objectForKey("testScoreSATArray") as Array
}
}
推荐答案
您收到原始错误的原因是,在 Swift 中,Array
是一个通用容器,用于保存特定类型的值.所以你可以有一个 Array
保存整数,或者一个 Array
保存字符串.但是你不能只有一个 Array
.数组包含的东西的类型是泛型参数,而 Swift 正在抱怨,因为它无法弄清楚该类型应该是什么.有时它可以从周围代码的上下文中推断出该类型,但并非总是如此,就像在这种情况下一样.
The reason you received your original error is that in Swift, Array
is a generic container that holds values of a specific type. So you can have an Array<Int>
that holds integers, or an Array<String>
that holds strings. But you can’t have just an Array
. The type of the thing the array contains is the generic parameter, and Swift is complaining because it can’t figure out what that type should be. Sometimes it can infer that type from the context of the code around it, but not always, as in this case.
您可以通过提供您存储的东西的类型来解决问题:
You can resolve the problem by giving the type of the thing you are storing:
IBAction func loadData(sender: AnyObject) {
if let testCompositeArray = defaults.objectForKey("testScoreSATArray") as? Array<Int> {
self.showDataLabel.text = toString(testCompositeArray)
}
}
你可以写更短的形式,而不是写Array
,[Int]
Instead of writing Array<Int>
, you can write the shorter form, [Int]
你也可以通过使用 NSArray
来解决这个问题,正如你所发现的.与 Array
不同,NSArray
不使用泛型,因为它起源于 Objective-C,它对 Swift 有不同的方法.相反,NSArray
只保存一种东西,一个 AnyObject
.这是一个可以指向任何类的实例的引用.
You can also solve the problem by using NSArray
, as you’ve found. Unlike Array
, NSArray
doesn’t use generics, since it originates in Objective-C which has a different approach to Swift. Instead, NSArray
holds only one kind of thing, an AnyObject
. This is is a reference that can point to instances of any class.
然而,使用 NSArray
和 AnyObject
有一个很大的缺点,那就是每次你使用它们包含的值时,你经常必须转换"这个值到一个真实的东西,比如一个整数或一个字符串.这可能会很痛苦,更糟糕的是,当您假设自己拥有一种东西而实际上拥有另一种东西时,有时会导致错误.Swift 通常鼓励您对类型进行更具体的处理,以避免出现此类错误.
However, there’s a big downside to using NSArray
and AnyObject
, which is that every time you use a value they contain, you often have to "cast" the value to a real thing, like an integer or a string. This can be a pain, and worse, sometimes can cause errors when you assume you have one kind of thing when actually you have another. Swift generally encourages you to be more specific about types to avoid errors like this.
这篇关于无法推断泛型参数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!