Search code examples
swiftstringswift-block

Join strings in a block


I have a block that updates the view for each String. In its object class I pass it by:

func eachFeaturesSection(block: ((String?) -> Void)?) {
propertyFeatures.forEach { feature in
  guard let feature = feature as? RealmString else {
    return
  }
  let features = feature.stringValue
    block?(features)
 }
}

and I will get it in ViewController, by:

listing!.eachFeaturesSection({ (features) in
  print(features)
  self.facilities = features!
})

So it will print as:

Optional("String 1")
Optional("String 2")

and self.facilities will be set to latest value which is self.facilities = "String 2"

cell.features.text = features // it will print String 2

So, how can I achieve to join all strings together in one string such as self.facilities = "String 1, String 2". I used .jointString does not work. Thank you for any help.


Solution

  • Maybe you could add them to an array of String elements and then, when done, call joined on that array.

    So something like this in your ViewController:

    var featuresArray = [String]()
    
    listing!.eachFeaturesSectionT({ (features) in
        print(features)
        featuresArray.append(features!)
    })
    
    //Swift 3 syntax
    cell.features.text = featuresArray.joined(separator: ", ")
    
    //Swift 2 syntax
    cell.features.text = featuresArray.joinWithSeparator(", ")
    

    Hope that helps you.