Adding NSArray Content to Swift Array

I use both swift and objective-c in my application.

I have a CustomClass, and I want to create a quick class for the class and add it to it from my objective-c class, which is called oldClass, which has an array of these objects in NSArray called arrayOfCustomClass.

var newArray = [CustomClass]() newArray += oldClass.arrayOfCustomClass 

This causes an error:

 '[(CustomClass)]' is not identical to 'CGFloat' 

Any help? thanks reza

+5
source share
3 answers

The problem is that Swift knows nothing about that in NSArray. You must explicitly point NSArray to [CustomClass] (and you better not lie, or you will crash at runtime).

0
source

It seems to work:

 newArray += oldClass.arrayOfCustomClass as AnyObject as [CustomClass] 
0
source

To do this safely, you just need to try the optional broadcast. If you think that NSArray has only elements of type CustomClass , you can do this:

 var newArray = [CustomClass]() if let customArray = oldClass.arrayOfCustomClass as? [CustomClass] { newArray += customArray } 

If you want to extract CustomClass elements (slightly different from what you requested, I know), this is the way:

 var newArray = [CustomClass]() for element: AnyObject in oldClass.arrayOfCustomClass { if let custom = element as? CustomClass { newArray.append(custom) } } 
0
source

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


All Articles