Swift 在块中连接字符串
我有一个更新每个字符串视图的块。在其对象类中,我将其传递:Swift 在块中连接字符串,swift,string,swift-block,Swift,String,Swift Block,我有一个更新每个字符串视图的块。在其对象类中,我将其传递: func eachFeaturesSection(block: ((String?) -> Void)?) { propertyFeatures.forEach { feature in guard let feature = feature as? RealmString else { return } let features = feature.stringValue block?(feature
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”
那么,如何实现将所有字符串连接到一个字符串中,例如
self.facilities=“string 1,string 2”
。我用过。jointString不起作用。谢谢您的帮助。也许您可以将它们添加到字符串
元素的数组中,然后,完成后,在该数组上调用已加入的
因此,在您的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(", ")
希望这对您有所帮助。也许您可以将它们添加到字符串
元素的数组中,然后,完成后,在该数组上调用已加入
因此,在您的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(", ")
希望对您有所帮助。self.facilities=features代码>什么都不做,但每次迭代都会不断更新值
更改行self.facilities=features代码>到self.facilities+=功能代码>或self.facilities=self.facilities+“,”+功能代码>self.facilities=功能代码>什么都不做,但每次迭代都会不断更新值
更改行self.facilities=features代码>到self.facilities+=功能代码>或self.facilities=self.facilities+“,”+功能代码>我会这样做(假设您的属性功能
是一个RealmString
数组):
Swift 3:
let string = (propertyFeatures.map { $0.stringValue }).joined(separator: ", ")
Swift 2:
let string = (propertyFeatures.map { $0.stringValue }).joinWithSeparator(", ")
下面是我的做法(假设您的propertyFeatures
是一个RealmString
数组):
Swift 3:
let string = (propertyFeatures.map { $0.stringValue }).joined(separator: ", ")
Swift 2:
let string = (propertyFeatures.map { $0.stringValue }).joinWithSeparator(", ")
非常感谢。但是它给出的错误是“类型“[String]”的值在这一行中没有成员“join”:cell.features.text=featuresArray.join(分隔符:“,”)是的,这成功了!featuresArray.joinWithSeparator(“,”)是的。非常感谢:)谢谢。但是它给出的错误是“类型“[String]的值”'在此行中没有成员'joined':cell.features.text=featuresArray.joined(分隔符:“,”)是的,这有效!特征:是的,是的。非常感谢:)谢谢。这一条:“self.facilities=self.facilities+features!”有效!但它打印出来的像,String1String2。在此实现中,是否可以用逗号分隔它们。self.facilities=self.facilities+“,”features,祝您有个美好的一天!谢谢这一条:“self.facilities=self.facilities+features!”有效!但它打印出来的像,String1String2。在此实现中,是否可以用逗号分隔它们。self.facilities=self.facilities+“,”features,祝您有个美好的一天!