【问题标题】:How to join the objects of NSMutableArray with a separator in Swift3如何在 Swift3 中使用分隔符连接 NSMutableArray 的对象
【发布时间】:2017-07-20 12:05:21
【问题描述】:

我有一个 NSMutableArray 声明如下:

var operatingDays = NSMutableArray()

接下来我将像这样将对象附加到数组中:

for operatingDays in forecast.operatingDays! {
              print(operatingDays.days)
              print(operatingDays.times)
              self.operatingDays.add(operatingDays.days)
            }

所以操作天数数组现在包含数组。

现在我想将每个数组转换为用空格分隔的字符串并将其显示给 UITableViewCell。为此,我使用 cellForRowAtIndexPath 的代码,如下所示:

cell.operationalDays.text = (operatingDays[indexPath.row] as AnyObject).joined(separator: " ")

但它显示错误:

【问题讨论】:

  • 强制转换为 [String] 而不是 AnyObject,您的数组是数组数组吗?
  • @ReinierMelian String 有一个名为joined的方法吗?
  • 是的,当然是
  • 再次查看我的评论,已编辑@mag_zbc
  • @ChelseaShawra 让我知道是否可行

标签: ios arrays uitableview swift3


【解决方案1】:

正如我在第一条评论中所说,将您的 operatingDays[indexPath.row] 转换为 [String] 它有效,试试这个

if let arrayOfStrings = operatingDays[indexPath.row] as? [String]
{
  cell.operationalDays.text = arrayOfStrings.joined(separator: " ")
}

希望对你有帮助

【讨论】:

    【解决方案2】:

    解决方法如下:

    var operatingDays = [Any]()
    cell.operationalDays.text = (operatingDays[indexPath.row] as? [String])?.joined(separator: " ")
    

    if let data = operatingDays[indexPath.row] as? [String] {
         cell.operationalDays.text = data.joined(separator: " ")
    }
    

    【讨论】:

      【解决方案3】:

      尝试联合数组如下:

      let tempArr = operatingDays[indexPath.row] as! NSArray
      cell.operationalDays.text = tempArr.componentsJoined(by: " ")
      

      【讨论】:

        【解决方案4】:

        将 AnyObject 转换为 Array 以使用连接函数。

        if let isArray = operatingDays[indexPath.row] as? [String] {
            //Now you can able to use joined function
            cell.operationalDays.text = isArray.joined(separator: " ")
        }
        

        【讨论】:

        • 我可以知道投反对票的原因吗?有什么问题让我知道我会更新自己。没有评论就不要使用否决票。谢谢
        猜你喜欢
        • 2016-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-09
        • 2017-08-14
        • 2018-12-24
        • 2016-06-04
        • 1970-01-01
        相关资源
        最近更新 更多