简体   繁体   English

如何在Swift3中使用分隔符连接NSMutableArray的对象

[英]How to join the objects of NSMutableArray with a separator in Swift3

I have got an NSMutableArray declared like as: 我有一个NSMutableArray声明为:

var operatingDays = NSMutableArray()

And next i am appending the objects into the array like this : 接下来,我将对象附加到数组中,如下所示:

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

So the operating days array now contains arrays. 因此,营业日数组现在包含数组。

控制台输出

Now i want to convert each array to string separated with a space and to show it to the UITableViewCell. 现在,我想将每个数组转换为用空格分隔的字符串,并将其显示给UITableViewCell。 For this i am using the code at cellForRowAtIndexPath like this: 为此,我正在像这样在cellForRowAtIndexPath使用代码:

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

But it shows the error : 但是它显示了错误:

在此处输入图片说明

As I said in my first comment, casting your operatingDays[indexPath.row] to [String] it works, Try with this 正如我在第一条评论中所述,将您的operatingDays[indexPath.row]强制转换为[String] ,请尝试一下

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

Hope this helps 希望这可以帮助

Solution is below: 解决方案如下:

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

or 要么

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

Try to joint array as below: 尝试按以下方式联合数组:

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

Cast AnyObject to Array to use joined function. 将AnyObject强制转换为Array以使用联合函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM