我知道如何通过编程来做到这一点,但我相信有一种内置的方式……
我使用过的每种语言都有某种对象集合的默认文本表示,当您试图将Array与字符串连接起来或将其传递给print()函数等时,它会吐出这些文本表示。苹果的Swift语言是否有一种内置的方式,可以轻松地将数组转换为字符串,或者我们总是必须显式地对数组进行字符串化?
我知道如何通过编程来做到这一点,但我相信有一种内置的方式……
我使用过的每种语言都有某种对象集合的默认文本表示,当您试图将Array与字符串连接起来或将其传递给print()函数等时,它会吐出这些文本表示。苹果的Swift语言是否有一种内置的方式,可以轻松地将数组转换为字符串,或者我们总是必须显式地对数组进行字符串化?
当前回答
当你也有struct数组时,你可以使用joined()来获得单个String。
struct Person{
let name:String
let contact:String
}
使用map() & joined()可以轻松生成字符串
PersonList.map({"\($0.name) - \($0.contact)"}).joined(separator: " | ")
输出:
Jhon - 123 | Mark - 456 | Ben - 789
其他回答
我的工作在NSMutableArray与componentsJoinedByString
var array = ["1", "2", "3"]
let stringRepresentation = array.componentsJoinedByString("-") // "1-2-3"
修改一个可选/非可选字符串数组
//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值,并附加其他值以给出一个连接字符串。
试试这个:
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: ",")
在Swift 4中
let array:[String] = ["Apple", "Pear ","Orange"]
array.joined(separator: " ")
为数组创建扩展:
extension Array {
var string: String? {
do {
let data = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
return String(data: data, encoding: .utf8)
} catch {
return nil
}
}
}