2016-03-15 62 views
0

我想將下面的字符串轉換爲NSMuableArray。Swift:將字符串轉換爲NSMutableArray

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

例如,我想在斯威夫特

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

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

將'String'更改爲'NSString',您可以繼續使用相同的功能。 –

+0

堆棧溢出是一個問題和答案網站,而不是代碼翻譯服務。嘗試先自己翻譯代碼,然後在遇到困難時找到我們,確保向我們展示[您嘗試過的](http://stackoverflow.com/help/mcve)。 – SmokeDispenser

回答

3

這裏執行以下Objective C的代碼是你的工作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"] 
0
var components: String = "library/book/science" 
var componentMutableArray = components.componentsSeparatedByString("/") 
componentMutableArray.append("astronomy") 
0

您需要使用NSString以調用componentsSeparatedByString函數,該函數將根據您選擇的分隔符將文本分割爲數組。

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