Iterate over NSMutableArray in Swift

I'm trying to iterate over NSMutableArray and it seems to behave differently than NSArray (at least in Xcode 6 beta 3)

class Element : NSObject { }

let a = NSArray()
let ma = NSMutableArray()

for e in a as Element[] { }
for e in ma as Element[] { } // compiler error: Cannot convert the expression type 'Element[]' to type 'Element[]'
for e in ma as NSArray as Element[] { }

I am confused why this is happening. Is there an explanation for this behavior or is it an Xcode / Swift error?

+4
source share
1 answer

Ok let's rephrase this to clarify the problem:

class Element : NSObject { }

// Create NSArray and NSMutableArray objective-c objects
let a1 = Element()
let a2 = Element()
let a = NSArray(objects: a1, a2)
let ma = NSMutableArray(objects: a1, a2)

let ae = a as [Element]        // ok
let mae = ma as [Element]      // error: 'Element' is not identical to 'AnyObject'
let mae2 = ma as NSArray as [Element]  // ok

Clearly, this is a mistake.

-1
source

Source: https://habr.com/ru/post/1548565/


All Articles