与铸造结构体的斯威夫特阵列一个NSArray,反之亦然NSUserDefaults的与使用问题 [英] Problems with casting a Swift array of Structs to an NSArray and vice versa to use with NSUserDefaults

查看:111
本文介绍了与铸造结构体的斯威夫特阵列一个NSArray,反之亦然NSUserDefaults的与使用问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行到桥结构体的斯威夫特阵列NSArrays的问题。我要存储结构体的一个NSUserDefaults的斯威夫特阵列。将NSUserDefaults的只接受一个NSArray。谁能告诉我这是做它的正确方法:

I'm running into the problem of bridging Swift arrays of Structs to NSArrays. I want to store a Swift Array of Structs in NSUserDefaults. NSUserDefaults will only accept an NSArray. Can somebody tell me whether this is the correct way of doing it:

首先,我声明数组的一些SwiftStruct和我的程序中使用它:

First I declare an array some SwiftStruct and use it in my program:

var favorites = [SomeSwiftStruct]()

然后保存它,我必须把它变成一个NSArray。有编译器不抱怨的唯一方法是上溯造型,如下所示:

Then to store it I have to turn it into an 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

推荐答案

问题是,编译器抱怨的事情是,你正在做的事情是行不通的。你不能在一个的NSArray 非Objective-C的对象(包括结构)存储。通过任何是添加足够的混淆,编译器将停止抱怨,但没有解决问题。展望

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. Going via Any is adding enough obfuscation that the compiler stops complaining, but doesn’t fix the issue.

它编译的原因是你的第二个是一个强制转换,即斯威夫特会做它,不管其是否有效。但是,这是危险的,因为它不会在运行时正常工作,所有你得到的是一个断言。事实上,在目前的1.2版雨燕这是处于测试阶段,这种已更名为为<!/ code>来表明它是危险的这个样子。

The reason it compiles is that your second as is a forcing cast, i.e. Swift will do it no matter whether its valid or not. 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! to indicate that it is dangerous like this.

要保存的东西,在 NSUserDefaults的你做必须有这使得它到的东西,可以存储(例如在您的斯威夫特结构的方法,数组字符串,这将是转换为一个的NSArray 的NSString S)的。

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 NSStrings).

这篇关于与铸造结构体的斯威夫特阵列一个NSArray,反之亦然NSUserDefaults的与使用问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆