[英]Append an array of strings to a string in Swift
I have an array of strings for one variable, and a string as another variable. 我有一个变量的字符串数组,另一个变量的字符串。 I'd like to append all of the strings in the collection to the single string.
我想将集合中的所有字符串追加到单个字符串中。
So for example I have: 所以我举例说:
var s = String()
//have the CSV writer create all the columns needed as an array of strings
let arrayOfStrings: [String] = csvReport.map{GenerateRow($0)}
// now that we have all the strings, append each one
arrayOfStrings.map(s.stringByAppendingString({$0}))
the line above fails. 上面的一行失败了。 I've tried every combination I can think of, but at the end of the day, I can't get it unless I just create a for loop to iterate through the entire collection, arrayOfStrings, and add it one by one.
我已经尝试了我能想到的每一个组合,但是在一天结束时,除非我只是创建一个for循环遍历整个集合,arrayOfStrings并逐个添加它,否则我无法得到它。 I feel like I can achieve this the same way using map or some other function.
我觉得我可以使用地图或其他功能以同样的方式实现这一点。
Any help? 有帮助吗?
Thanks! 谢谢!
You can use joinWithSeparator : 您可以使用joinWithSeparator :
let stringArray = ["Hello", "World"]
let sentence = stringArray.joined(separator: " ") // "Hello World"
You could convert your array to string using joinWithSeparator(String)
here is an example 您可以使用
joinWithSeparator(String)
将数组转换为字符串,这是一个示例
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
source: [ How do I convert a Swift Array to a String? 来源:[ 如何将Swift数组转换为字符串? ]
]
There are at least two options here. 这里至少有两个选择。 The most semantic choice is likely
joinWithSeparator
on the [String]
object. 最具语义的选择可能是
[String]
对象上的joinWithSeparator
。 This concatenates every string in the array, placing the separator provided as a parameter between each string. 这将连接数组中的每个字符串,将分隔符作为参数提供在每个字符串之间。
let result = ["a", "b", "c", "d"].joinWithSeparator("")
An alternative is to use a functional reduce
and the + function operator which concatenates strings. 另一种方法是使用函数
reduce
和+函数运算符来连接字符串。 This may be preferred if you want to do additional logic as part of the combine. 如果您想要将其他逻辑作为组合的一部分,这可能是首选。 Both example code produce the same result.
两个示例代码都产生相同的结果。
let result = ["a", "b", "c", "d"].reduce("", combine: +)
It's also worth noting the second options is transferrable to any type that can be added, whereas the first only works with a sequence of strings, as it is defined on a protocol extension of SequenceType where Generator.Element == String
. 值得注意的是,第二个选项可以转移到任何可以添加的类型,而第一个选项只适用于一系列字符串,因为它是在
SequenceType where Generator.Element == String
的协议扩展中定义的, SequenceType where Generator.Element == String
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.