Swift:将String转换为NSMutableArray

时间:2016-03-15 07:26:01

标签: ios objective-c swift nsmutablearray nsarray

我想将以下字符串转换为NSMuableArray。

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

例如,我想在Swift中执行以下目标c代码

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

NSMutableArray *componentsMutableArray = [[NSMutableArray alloc] initWithArray:componentsArray];
[componentsMutableArray addObject:@"astronomy"];

3 个答案:

答案 0 :(得分:3)

这是您正在使用的快速代码:

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您需要使用NSString来调用componentsSeparatedByString函数,该函数会根据您选择的分隔符将文本拆分为数组。

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