将NSArray转换为Swift数组< T> [英] Convert NSArray to Swift Array<T>
问题描述
在CoreData中,我定义了一个有序对多关系。这种关系在Swift中定义如下:
@NSManaged var types:NSMutableArray
但是,为了使用Swift是最好的,我想使用一个普通的Swift数组,如
Type [] $ c $ c>。但是,CoreData强制我使用
,但感觉像一个hack /解决方法。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 []
然后修改你的感觉。你正在做的正是你如何type-cast /将
NSArray
转换为Array< Type& ]
。
一个NSArray总是到达Swift包含
AnyObject
Array< AnyObject>
,akaAnyObject []
)。如果你知道它包含了所有的类型,它是由你决定的,你如何做它正是你应该做的。
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 useNS(Mutable)Array
. How can I type-cast / convert theNSArray
toArray<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
toArray<Type>[]
."An NSArray always arrives into Swift as containing
AnyObject
(i.e. anArray<AnyObject>
, akaAnyObject[]
). 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 ofAnyObject
and will still have to be cast down to a specific type.这篇关于将NSArray转换为Swift数组< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!