Search code examples
iosobjective-cswiftnsmutablearraynsarray

Swift: Convert String to NSMutableArray


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"];

Solution

  • 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"]