swift - 在 block 中连接字符串

标签 swift string swift-block

我有一个 block 可以更新每个字符串的 View 。在它的对象类中,我通过它:

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

我将通过以下方式在 ViewController 中获取它:

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

所以它将打印为:

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

并且 self.facilities 将设置为最新值,即 self.facilities = "String 2"

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

那么,我怎样才能将所有字符串连接到一个字符串中,例如 self.facilities = "String 1, String 2"。我用 .jointString 不起作用。感谢您的帮助。

最佳答案

也许您可以将它们添加到 String 元素的数组中,然后在完成后对该数组调用 joined

所以在你的 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(", ")

希望对你有帮助。

关于swift - 在 block 中连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40906738/

相关文章:

Swift 忽略 block 签名中定义的参数类型

ios - 当我在 block 中使用 self 时,我得到一个 nil。但是 self 没有释放

ios - 在 Realm 中进行大规模更新的首选方法?

swift - 我们什么时候可以开始向 iOS App Store 提交使用 Swift 编程语言编写的应用程序?

python - 如何在给定不需要的字符列表的情况下去除字符串? Python

c - 如何在c中正确实现strcpy?

ios - 如何编写一个 block 将值从一个类返回到另一个类?

ios - 出现键盘时以编程方式更新约束

ios - 如何在 Xcode 的 UITest 中访问当前的 UIViewController?

c++ - 在 C++ 中使用 ncurses 读取字符串