简体   繁体   中英

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

I have got an NSMutableArray declared like as:

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. For this i am using the code at cellForRowAtIndexPath like this:

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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