如何将Swift数组转换为字符串?


353

我知道如何以编程方式做到这一点,但是我敢肯定有一种内置的方式...

我使用的每种语言都有一组对象的默认文本表示形式,当您尝试将Array与字符串连接起来或将其传递给print()函数时,它会吐出。Apple的Swift语言是否可以有一种轻松地将数组转换为字符串的内置方法,还是在对数组进行字符串化时始终必须明确?


3
Swift 4: array.description或者如果您需要自定义分隔符array.joined(separator: ",")
Jonathan Solorzano,

Answers:


697

如果数组包含字符串,则可以使用Stringjoin方法:

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

2
@Andrej:它同时适用于1.2和2.0。您是否正在使用字符串数组?
Antonio

1
安东尼奥,对不起,我不好。我的阵列出现问题。现在,我可以确认您的解决方案有效。:)
Andrej

12
"-".join(array)在Swift 2,Xcode 7 Beta 6中不再可用,请尝试使用array.joinWithSeparator("-")
Harry Ng,

87
joinWithSeparator仅适用于字符串数组。如果您有其他对象数组,map请先使用。例如,[1, 2, 3].map({"\($0)"}).joinWithSeparator(",")
Dmitry

3
@Dmitry不要使用字符串内插soley转换为字符串。在String上使用初始化器会更好
亚历山大-恢复莫妮卡

130

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


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

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

print(string)
// prints "John"

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

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

print(string) // prints: "BobDanBryan"

Strings 数组变成a String,并在单词之间使用分隔符:

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

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

Strings 数组转换为String,并在字符之间使用分隔符:

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"

Floats 数组转换为a 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"

我有一个字符串,看起来像:“ [1,2,3]”。有什么方法可以轻松地将其转换为数组[Int]?容易地,即.description的相反含义?
user2363025

@ user2363025 uni可以使用JSON解码器。try JSONDecoder().decode([Int].self, from: Data(string.utf8))
Leo Dabus

48

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
}

23

迅捷3

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

1
我会说这是[“ I Love”,“ Swift”]。joined(分隔符:““)
Loebre

15

在Swift 4中

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

array.joined(separator: " ")

11

由于没有人提到reduce,因此这里是:

[0, 1, 1, 0].map {"\($0)"}.reduce("") {$0 + $1 } // "0110"

本着函数式编程的精神🤖


3
不错的处理方式,谢谢...添加了一个较短的命令行末尾: [0,1,1,0].map{"\($0)"}.reduce("",+)。😉
XLE_22

@ XLE_22[0,1,1,0].map(String.init).joined()
Leo Dabus

8

更改可选/非可选字符串的数组

//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)

在这里,flatMapcompactMap跳过数组中的nil值,并附加其他值以提供连接的字符串。


3
@YashBedi在Swift 4中,我们使用compactMap代替flatMap
Agent Smith

“ $”是什么意思?
奥古斯托

2
@Augusto Swift自动为内联闭包提供速记参数名称,可用于通过名称$ 0,$ 1,$ 2引用闭包参数的值。在这里,$ 0指的是闭包的第一个String参数。
特工史密斯

4

我的工作与组件JoinedByString NSMutableArray

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

4

在Swift 2.2中,您可能必须将数组转换为NSArray才能使用componentsJoinedByString(“,”)

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

顺便说一下,这只是对Objective-C的快速翻译。
穆罕默德·泽山

3

如果要抛空数组中的空字符串。

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

如果还要过滤nil值:

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

1
非常优雅,谢谢:)
CheshireKat

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

结果将是>>> Mani Singh iOS Developer


1

与您描述的Swift等效的是字符串插值。如果您正在考虑像JavaScript这样的事情"x" + array,那么Swift中的等效项是"x\(array)"

作为一般说明,字符串插值与Printable协议之间存在重要区别。仅某些类符合Printable每个类都可以以某种方式插入字符串。这在编写泛型函数时很有用。您不必局限于Printable上课。


1

您可以使用打印功能打印任何对象

或用于\(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]"

1

为创建扩展名Array

extension Array {

    var string: String? {

        do {

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

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

        } catch {

            return nil
        }
    }
}

0

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

// 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!)

0

如果您有字符串数组列表,则转换为Int

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

它会给你字符串值


0

对于任何元素类型

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;
    }
}

0

尝试这个:

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

-1

对于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
    }
}

-1

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

String(tobeFormattedString)


不,这不起作用。String没有能够执行此操作的初始化程序。您正在使用自定义扩展程序或第三方库,或者只是简单地犯了一个错误。
Eric Aya
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.