0
votes

I have an array in a function. Look below.

    var HeadlinesString:NSString = Headlines["text"] as NSString
    var headlinesArray: NSArray = HeadlinesString.componentsSeparatedByString("\n") as NSArray

I also have an empty array inside the class. Look below

var headlinesLabels: NSArray = NSArray ()

I want to copy the headlinesArray to the headlinesLabels so I can use the array in another function. How can I do this? Should I copy the headlinesArray to the headlinesLabels? Is there a better way to do it?

I am not sure what to do and how to do it. All suggestions welcomed.

Thanks

1
At the risk of sounding glib – if you were using Array instead of NSArray this would be a lot less of a concern - Airspeed Velocity

1 Answers

1
votes

You've got different possibilities. First you can add a return-value to your function and return your string-array.

func yourFunction()->[String]{
    var headlinesString:String = Headlines["text"] as String
    var headlinesArray:[String] = headlinesString.componentsSeparatedByString("\n")
    return headlinesArray
}

var headLinesLabels = yourFunction()

Or you can just set the value of your headLinesLabels in the function itself:

func yourFunction(){
    var headlinesString:String = Headlines["text"] as String
    var headlinesArray:[String] = headlinesString.componentsSeparatedByString("\n")
    headLinesLabels = headLinesArray   
}

That way you don't need to return a value but you set it right in your function. But I would recommend to use the first possibility.

As you maybe noticed, I've edited your existing code a bit. First you should use String instead of NSString if you are using Swift.

Also variable-names should always be camelCase. So change HeadlinesString to headlinesString.

Also you don't need to cast your objects you receive from the componentsSeparatedByString method into an NSArray, but you can use [String] to cast it to an array with String elements. The same with the headLinesLabels variable. Just initialize it like that:

var headlinesLabels:[String]!

That way, Swift knows that this array should contain String elements and you can set it at anytime later like that:

 headlinesLabels = /*yourStringArray*/