joined()
方法通过连接数组中的所有元素,并用指定的分隔符分隔,从而返回一个新的字符串。
示例
var message = ["Swift", "is","fun"]
// join all elements of array with space between them
var newString = message.joined(separator:" ")
print(newString)
// Output: Swift is fun
joined() 语法
joined()
方法的语法是
array.joined(separator: delimiter)
其中,array 是 Array
类的一个对象。
joined() 参数
joined()
方法接受一个参数
- delimiter (可选) - 用于连接元素的the separator(分隔符)。
注意:如果我们不带任何参数调用 joined()
,元素将不带分隔符地连接在一起。
joined() 返回值
- 返回一个包含所有数组元素并用分隔符连接而成的字符串
示例:Swift joined()
var brands = ["Dell", "HP", "Apple"]
// join elements with no separator
var result1 = brands.joined()
// join elements with space between them
var result2 = brands.joined(separator:" ")
// join elements with comma between them
var result3 = brands.joined(separator:", ")
print(result1)
print(result2)
print(result3)
输出
DellHPApple Dell HP Apple Dell, HP, Apple
在这里,我们可以看到 joined()
方法将所有数组元素转换为一个字符串,并用指定的分隔符分隔每个元素。