我知道如何通过编程来做到这一点,但我相信有一种内置的方式……

我使用过的每种语言都有某种对象集合的默认文本表示,当您试图将Array与字符串连接起来或将其传递给print()函数等时,它会吐出这些文本表示。苹果的Swift语言是否有一种内置的方式,可以轻松地将数组转换为字符串,或者我们总是必须显式地对数组进行字符串化?


如果数组包含字符串,你可以使用String的join方法:

var array = ["1", "2", "3"]

let stringRepresentation = "-".join(array) // "1-2-3"

在Swift 2中:

var array = ["1", "2", "3"]

let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

如果您想使用特定的分隔符(连字符、空格、逗号等),这可能很有用。

否则,你可以简单地使用description属性,它返回数组的字符串表示形式:

let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"

提示:任何实现Printable协议的对象都有一个description属性。如果你在自己的类/结构中采用该协议,你也可以使它们打印友好

在Swift 3中

join变为joined,示例[nil, "1", "2"].flatMap({$0}).joined() joinWithSeparator变成了joined(separator:)(仅适用于字符串数组)

在Swift 4中

var array = ["1", "2", "3"]
array.joined(separator:"-")

Swift等价于你所描述的是字符串插值。如果你考虑JavaScript做“x”+数组,在Swift中等价的是“x\(数组)”。

一般来说,字符串插值和Printable协议之间有一个重要的区别。只有特定的类符合Printable。每个类都可以以某种方式插入字符串。这在编写泛型函数时很有帮助。您不必将自己限制在Printable类上。


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
}

我的工作在NSMutableArray与componentsJoinedByString

var array = ["1", "2", "3"]
let stringRepresentation = array.componentsJoinedByString("-") // "1-2-3"

使用Swift 5,根据您的需要,您可以选择以下Playground示例代码之一来解决您的问题。


将字符数组转换为不带分隔符的字符串:

let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)

print(string)
// prints "John"

将String数组转换为不带分隔符的String:

let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")

print(string) // prints: "BobDanBryan"

将字符串数组转换为单词之间带有分隔符的字符串:

let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")

print(string) // prints: "Bob Dan Bryan"

将字符串数组转换为字符之间带有分隔符的字符串:

let stringArray = ["car", "bike", "boat"]
let characterArray = stringArray.flatMap { $0 }
let stringArray2 = characterArray.map { String($0) }
let string = stringArray2.joined(separator: ", ")

print(string) // prints: "c, a, r, b, i, k, e, b, o, a, t"

将float数组转换为数字之间带有分隔符的String:

let floatArray = [12, 14.6, 35]
let stringArray = floatArray.map { String($0) }
let string = stringArray.joined(separator: "-")

print(string)
// prints "12.0-14.6-35.0"

let arrayTemp :[String] = ["Mani","Singh","iOS Developer"]
    let stringAfterCombining = arrayTemp.componentsJoinedByString(" ")
   print("Result will be >>>  \(stringAfterCombining)")

结果将>>> Mani Singh iOS开发者


可以使用print函数打印任何对象

或者使用\(name)将任何对象转换为字符串。

例子:

let array = [1,2,3,4]

print(array) // prints "[1,2,3,4]"

let string = "\(array)" // string == "[1,2,3,4]"
print(string) // prints "[1,2,3,4]"

在Swift 2.2中,你可能不得不将数组转换为NSArray来使用componentsJoinedByString(",")

let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")

斯威夫特3

["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")

对于swift 3:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == phoneField
    {
        let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
        let components = newString.components(separatedBy: NSCharacterSet.decimalDigits.inverted)

        let decimalString = NSString(string: components.joined(separator: ""))
        let length = decimalString.length
        let hasLeadingOne = length > 0 && decimalString.character(at: 0) == (1 as unichar)

        if length == 0 || (length > 10 && !hasLeadingOne) || length > 11
        {
            let newLength = NSString(string: textField.text!).length + (string as NSString).length - range.length as Int

            return (newLength > 10) ? false : true
        }
        var index = 0 as Int
        let formattedString = NSMutableString()

        if hasLeadingOne
        {
            formattedString.append("1 ")
            index += 1
        }
        if (length - index) > 3
        {
            let areaCode = decimalString.substring(with: NSMakeRange(index, 3))
            formattedString.appendFormat("(%@)", areaCode)
            index += 3
        }
        if length - index > 3
        {
            let prefix = decimalString.substring(with: NSMakeRange(index, 3))
            formattedString.appendFormat("%@-", prefix)
            index += 3
        }

        let remainder = decimalString.substring(from: index)
        formattedString.append(remainder)
        textField.text = formattedString as String
        return false
    }
    else
    {
        return true
    }
}

修改一个可选/非可选字符串数组

//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值,并附加其他值以给出一个连接字符串。


为数组创建扩展:

extension Array {

    var string: String? {

        do {

            let data = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])

            return String(data: data, encoding: .utf8)

        } catch {

            return nil
        }
    }
}

在Swift 4中

let array:[String] = ["Apple", "Pear ","Orange"]

array.joined(separator: " ")

如果你想在数组中丢弃空字符串。

["Jet", "Fire"].filter { !$0.isEmpty }.joined(separator: "-")

如果你也想过滤nil值:

["Jet", nil, "", "Fire"].flatMap { $0 }.filter { !$0.isEmpty }.joined(separator: "-")

如果你的问题是这样的: tobeFormattedString = ["a", "b", "c"] 输出= "abc"

String(tobeFormattedString)


对于某些语言(如希伯来语或日语),分隔符可能不是一个好主意。 试试这个:

// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)

对于其他数据类型,分别为:

// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)

如果你有字符串数组列表,那么转换为Int

let arrayList = list.map { Int($0)!} 
     arrayList.description

它会给你字符串值


对于任何元素类型

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: ",")

当您想要将结构类型的列表转换为字符串时,请使用此方法

struct MyStruct {
  var name : String
  var content : String
}

let myStructList = [MyStruct(name: "name1" , content: "content1") , MyStruct(name: "name2" , content: "content2")]

然后像这样隐藏你的数组

let myString = myStructList.map({$0.name}).joined(separator: ",")

将产生===> "name1,name2"


现在,在iOS 13+和macOS 10.15+中,我们可能会使用ListFormatter:

let formatter = ListFormatter()

let names = ["Moe", "Larry", "Curly"]
if let string = formatter.string(from: names) {
    print(string)
}

这将生成一个漂亮的自然语言字符串表示列表。美国用户将看到:

老谋子,拉里和卷毛

它将支持任何语言,其中(a)你的应用程序已本地化;并且(b)配置了用户的设备。例如,一个德国用户的应用程序支持德语本地化,他会看到:

莫、拉瑞、克利


当你也有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  

如果你想转换自定义对象数组为字符串或逗号分隔字符串(csv),你可以使用

 var stringIds = (self.mylist.map{$0.id ?? 0}).map{String($0)}.joined(separator: ",")

归功于:莫迪 post:将int数组转换为逗号分隔的字符串


你可以使用循环来完成这个任务。或者使用地图。

通过映射:

let array = ["one" , "two" , "three"]
    
array.map({$0}).joined(seperator : ",")

在分隔符中,你可以修改字符串。

Output-> ("one,two,three")