2

I want to convert following String to NSMuableArray.

var components: String = "library/book/science"

For example, I want to perform the following objective c code in Swift

NSArray *componentsArray = [@"library/book/science" componentsSeparatedByString:@"/"];

NSMutableArray *componentsMutableArray = [[NSMutableArray alloc] initWithArray:componentsArray];
[componentsMutableArray addObject:@"astronomy"];
Prashanth Rajagopalan
  • 718
  • 1
  • 10
  • 27
  • change `String` to `NSString` and you can keep using same functions. – Shamas S Mar 15 '16 at 07:29
  • Stack Overflow is a Question and Answer site, not a code translation service. Try to translate the code yourself first, then come to us when you are stuck, making sure to show us [what you have tried](http://stackoverflow.com/help/mcve). – Tobi Nary Mar 15 '16 at 08:43

3 Answers3

8

Here is your working swift code:

var components: String = "library/bool/science"

let componentsArray = components.componentsSeparatedByString("/")     //["library", "bool", "science"]

let componentsMutableArray = NSMutableArray(array: componentsArray)   //["library", "bool", "science"]

componentsMutableArray.addObject("astronomy")                         //["library", "bool", "science", "astronomy"]
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
0
var components: String = "library/book/science"
var componentMutableArray = components.componentsSeparatedByString("/")
componentMutableArray.append("astronomy")
Muzahid
  • 5,072
  • 2
  • 24
  • 42
0

You need to use NSString in order to call the componentsSeparatedByString function that will split your text into an array based on the separator of your choice.

let theString = NSString(string: "library/book/science")
let components = theString.componentsSeparatedByString("/")
AlexCsl
  • 1
  • 1