Convert NSArray to Swift Array

后端 未结 4 1672
终归单人心
终归单人心 2020-12-29 03:23

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

@NSManaged var types : NSMutableArray
<         


        
相关标签:
4条回答
  • 2020-12-29 04:01

    Enumerate them that way :

    for type in types.array {
        // Do something
    }
    

    Or use simply the array property of the NSOrderedSet you are using, like so :

    types.array
    
    0 讨论(0)
  • 2020-12-29 04:02

    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.

    0 讨论(0)
  • 2020-12-29 04:08

    The following is a working piece of code from one of my projects that might help?

    if let rawArray = rawData as? NSArray,
       let castArray = rawArray as? Array< Dictionary< String, AnyObject > >
       { 
           // etc... 
       }
    

    It works, although I'm not sure it would be considered optimal.

    0 讨论(0)
  • 2020-12-29 04:09

    You are going to have to create a new generic array and manually populate it as follows:

        var result = Type[]()
    
        for item : AnyObject in self {
            //  Keep only objC objects compatible with OutType
            if let converted = bridgeFromObjectiveC(item, Type.self) {
                result.append(converted)
            }
        }
    
    0 讨论(0)
提交回复
热议问题