将NSArray转换为Swift数组< T> [英] Convert NSArray to Swift Array<T>

查看:157
本文介绍了将NSArray转换为Swift数组< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CoreData中,我定义了一个有序对多关系。这种关系在Swift中定义如下:

  @NSManaged var types:NSMutableArray 
但是,为了使用Swift是最好的,我想使用一个普通的Swift数组,如 Type [] c>。但是,CoreData强制我使用 NS(Mutable)Array 。如何将 NSArray 输入/转换为数组< Type> []



显然,混淆起因于以下错误:

  let array = obj.types as T [] //无法将表达式的类型Node []转换为类型$ T2

被编辑接受:

  let array = obj.types as AnyObject [] as T [] //无投诉


解决方案


code> obj.types.allObjects as Type [] ,但感觉像一个hack /解决方法。


然后修改你的感觉。你正在做的正是你如何type-cast /将 NSArray 转换为 Array< Type& ]



一个NSArray总是到达Swift包含 AnyObject Array< AnyObject> ,aka AnyObject [] )。如果你知道它包含了所有的类型,它是由你决定的,你如何做它正是你应该做的。



EDIT 在Swift 2.0和新的iOS 9 API中,NSArray通常会正确输入,而且不需要转换。



EDIT 2 在Swift 3.0中,不正确输入的NSArray虽然不常见,但会包含 Any 而不是 AnyObject ,并且仍然必须强制转换为特定类型。


In CoreData I have defined an ordered to-many relationship. This relationship is defined in Swift like this:

@NSManaged var types : NSMutableArray

However, to use Swift at it's best, I want to use a normal Swift array like Type[]. However, CoreData forces me to use NS(Mutable)Array. How can I type-cast / convert the NSArray to Array<Type>[]?

Apparently the confusion arises from the following error:

let array = obj.types as T[] // Cannot convert expression's type 'Node[]' to type '$T2'

While this is accepted by the editor:

let array = obj.types as AnyObject[] as T[] // No complaint

解决方案

I'm currently using obj.types.allObjects as Type[], but that feels like a hack/workaround.

Then revise your feelings. What you're doing is exactly how you do "type-cast / convert the NSArray to Array<Type>[]."

An NSArray always arrives into Swift as containing AnyObject (i.e. an Array<AnyObject>, aka AnyObject[]). Casting it down to a specific type, if you know that it contains all one type, is up to you, and how you are doing it is exactly what you are supposed to do.

EDIT In Swift 2.0 and the new iOS 9 APIs, an NSArray will often arrive correctly typed, and no cast will be needed.

EDIT 2 In Swift 3.0, an NSArray that is not correctly typed, though uncommon, will arrive as containing Any instead of AnyObject and will still have to be cast down to a specific type.

这篇关于将NSArray转换为Swift数组&lt; T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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