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"];
2
  • change String to NSString and you can keep using same functions. Commented Mar 15, 2016 at 7: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. Commented Mar 15, 2016 at 8:43

3 Answers 3

7

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"]
Sign up to request clarification or add additional context in comments.

Comments

0
var components: String = "library/book/science"
var componentMutableArray = components.componentsSeparatedByString("/")
componentMutableArray.append("astronomy")

Comments

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("/")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.