Swift: 将字符串转换为 NSMutableArray

Swift: Convert String to NSMutableArray

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

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

例如我想在Swift

中执行下面的objective c代码
NSArray *componentsArray = [@"library/book/science" componentsSeparatedByString:@"/"];

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

这是您的工作 swift 代码:

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"]
var components: String = "library/book/science"
var componentMutableArray = components.componentsSeparatedByString("/")
componentMutableArray.append("astronomy")

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

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