[英]Problems with casting a Swift array of Structs to an NSArray and vice versa to use with NSUserDefaults
I'm running into the problem of bridging Swift arrays of Structs to NSArrays. 我遇到了将Structs的Swift数组桥接到NSArrays的问题。 I want to store a Swift Array of Structs in NSUserDefaults.
我想在NSUserDefaults中存储结构的Swift数组。 NSUserDefaults will only accept an NSArray.
NSUserDefaults将仅接受NSArray。 Can somebody tell me whether this is the correct way of doing it:
有人可以告诉我这是否是正确的方法:
First I declare an array some SwiftStruct and use it in my program: 首先,我在SwiftStruct中声明一个数组,并在程序中使用它:
var favorites = [SomeSwiftStruct]()
Then to store it I have to turn it into an NSArray. 然后要存储它,我必须将其转换为NSArray。 The only way to have the compiler not complain is to upcast it as follows:
使编译器不抱怨的唯一方法是按如下所示进行转换:
let tempArray = favorites as Any as NSArray
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(tempArray, forKey: "favorites")
Then retrieving it I wanted to try this: 然后检索它,我想尝试一下:
if let tempArray = defaults.objectForKey("favorites") as NSArray as Any as? [SomeSwiftStruct]{
favorits = tempArray}
Unfortunately I can't yet test whether this works. 不幸的是我还不能测试这是否有效。 For now I only know there are no compiler complaints
现在我只知道没有编译器投诉
The problem is, the thing the compiler is complaining about is that you are doing something that won't work. 问题是,编译器抱怨的是您正在执行无法执行的操作。 You cannot store non-Objective-C objects (including structs) in an
NSArray
. 您不能在
NSArray
存储非Object-C对象(包括结构)。 Going via Any
is adding enough obfuscation that the compiler stops complaining, but doesn't fix the issue. 通过
Any
会增加足够的混淆,编译器会停止抱怨,但不能解决问题。
The reason it compiles is that your second as
is a forcing cast, ie Swift will do it no matter whether its valid or not. 它编译的原因是你的第二个
as
是迫使投,即斯威夫特将做到这一点,无论其是否有效。 But this is dangerous, since it will not work at runtime, all you'll get is an assertion. 但这很危险,因为它在运行时不起作用,因此您只会得到一个断言。 In fact, in the current 1.2 version of Swift that's in beta, this kind of
as
has been renamed as!
实际上,在当前的1.2版本的Swift中,这种
as
已被重命名as!
to indicate that it is dangerous like this. 表示这样很危险。
To store stuff in NSUserDefaults
you're doing to have to have a method on your Swift struct that renders it into something that can be stored (for example, an array of strings, which will be convertible to an NSArray
of NSString
s). 要将内容存储在
NSUserDefaults
您需要在Swift结构上具有一个将其呈现为可以存储的内容的方法(例如,字符串数组,该数组可以转换为NSString
的NSArray
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.