我知道如何通过编程来做到这一点,但我相信有一种内置的方式……
我使用过的每种语言都有某种对象集合的默认文本表示,当您试图将Array与字符串连接起来或将其传递给print()函数等时,它会吐出这些文本表示。苹果的Swift语言是否有一种内置的方式,可以轻松地将数组转换为字符串,或者我们总是必须显式地对数组进行字符串化?
我知道如何通过编程来做到这一点,但我相信有一种内置的方式……
我使用过的每种语言都有某种对象集合的默认文本表示,当您试图将Array与字符串连接起来或将其传递给print()函数等时,它会吐出这些文本表示。苹果的Swift语言是否有一种内置的方式,可以轻松地将数组转换为字符串,或者我们总是必须显式地对数组进行字符串化?
当前回答
Swift等价于你所描述的是字符串插值。如果你考虑JavaScript做“x”+数组,在Swift中等价的是“x\(数组)”。
一般来说,字符串插值和Printable协议之间有一个重要的区别。只有特定的类符合Printable。每个类都可以以某种方式插入字符串。这在编写泛型函数时很有帮助。您不必将自己限制在Printable类上。
其他回答
对于任何元素类型
extension Array {
func joined(glue:()->Element)->[Element]{
var result:[Element] = [];
result.reserveCapacity(count * 2);
let last = count - 1;
for (ix,item) in enumerated() {
result.append(item);
guard ix < last else{ continue }
result.append(glue());
}
return result;
}
}
试试这个:
let categories = dictData?.value(forKeyPath: "listing_subcategories_id") as! NSMutableArray
let tempArray = NSMutableArray()
for dc in categories
{
let dictD = dc as? NSMutableDictionary
tempArray.add(dictD?.object(forKey: "subcategories_name") as! String)
}
let joinedString = tempArray.componentsJoined(by: ",")
修改一个可选/非可选字符串数组
//Array of optional Strings
let array : [String?] = ["1",nil,"2","3","4"]
//Separator String
let separator = ","
//flatMap skips the nil values and then joined combines the non nil elements with the separator
let joinedString = array.flatMap{ $0 }.joined(separator: separator)
//Use Compact map in case of **Swift 4**
let joinedString = array.compactMap{ $0 }.joined(separator: separator
print(joinedString)
这里是flatMap, compactMap跳过数组中的nil值,并附加其他值以给出一个连接字符串。
斯威夫特3
["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")
Swift 2.0 Xcode 7.0 beta 6以上使用joinWithSeparator()代替join():
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
joinWithSeparator被定义为SequenceType的扩展
extension SequenceType where Generator.Element == String {
/// Interpose the `separator` between elements of `self`, then concatenate
/// the result. For example:
///
/// ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
@warn_unused_result
public func joinWithSeparator(separator: String) -> String
}