0

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.

Umit Kaya
  • 5,771
  • 3
  • 38
  • 52

3 Answers3

5

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.

pbodsk
  • 6,787
  • 3
  • 21
  • 51
1

self.facilities = features! is doing nothing but keeps updating the value every iteration

Change the line self.facilities = features! to self.facilities += features! or self.facilities = self.facilities + ", " + features!

Pang Ho Ming
  • 1,299
  • 10
  • 29
  • Thanks. This one: "self.facilities = self.facilities + features!" works! but it prints like, String1String2. Any way to seperate them with a comma in this implementation. – Umit Kaya Dec 01 '16 at 10:01
  • self.facilities = self.facilities + ", " + features! , have a nice day! – Pang Ho Ming Dec 01 '16 at 10:03
0

Here's how I'd do it (assuming your propertyFeatures is an array of RealmString):

Swift 3:

let string = (propertyFeatures.map { $0.stringValue }).joined(separator: ", ")

Swift 2:

let string = (propertyFeatures.map { $0.stringValue }).joinWithSeparator(", ")
Jeremy
  • 1,461
  • 12
  • 26