【问题标题】:Swift: Convert String to NSMutableArray [duplicate]Swift:将字符串转换为 NSMutableArray [重复]
【发布时间】:2016-06-30 12:25:10
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • String改成NSString就可以继续使用同样的功能了。
  • Stack Overflow 是一个问答网站,而不是代码翻译服务。尝试先自己翻译代码,遇到困难再找我们,一定要告诉我们what you have tried

标签: ios objective-c swift nsmutablearray nsarray


【解决方案1】:

这是您的 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"]

【讨论】:

    【解决方案2】:
    var components: String = "library/book/science"
    var componentMutableArray = components.componentsSeparatedByString("/")
    componentMutableArray.append("astronomy")
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2015-08-22
        • 1970-01-01
        • 2017-10-09
        • 1970-01-01
        • 2021-10-18
        • 2017-07-20
        • 1970-01-01
        • 2011-02-02
        • 1970-01-01
        相关资源
        最近更新 更多