简体   繁体   English

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

[英]How do I convert a Swift Array to a String?

I know how to programmatically do it, but I'm sure there's a built-in way...我知道如何以编程方式做到这一点,但我确信有一种内置的方式......

Every language I've used has some sort of default textual representation for a collection of objects that it will spit out when you try to concatenate the Array with a string, or pass it to a print() function, etc. Does Apple's Swift language have a built-in way of easily turning an Array into a String, or do we always have to be explicit when stringifying an array?我使用的每种语言都有一些对象集合的默认文本表示,当您尝试将数组与字符串连接或将其传递给 print() function 等时,它将吐出这些对象集合。Apple 的 Swift 语言是否有一种内置的方法可以轻松地将数组转换为字符串,还是在对数组进行字符串化时总是必须明确?

If the array contains strings, you can use the String 's join method:如果数组包含字符串,则可以使用Stringjoin方法:

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

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

In Swift 2 :Swift 2 中

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

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

This can be useful if you want to use a specific separator (hypen, blank, comma, etc).如果您想使用特定的分隔符(连字符、空格、逗号等),这会很有用。

Otherwise you can simply use the description property, which returns a string representation of the array:否则,您可以简单地使用description属性,它返回数组的字符串表示形式:

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

Hint: any object implementing the Printable protocol has a description property.提示:任何实现Printable协议的对象都有一个description属性。 If you adopt that protocol in your own classes/structs, you make them print friendly as well如果您在自己的类/结构中采用该协议,您也可以使它们打印友好

In Swift 3斯威夫特 3

  • join becomes joined , example [nil, "1", "2"].flatMap({$0}).joined() join变为joined ,例如[nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator becomes joined(separator:) (only available to Array of Strings) joinWithSeparator变为joined(separator:) (仅适用于字符串数组)

In Swift 4斯威夫特 4

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

With Swift 5, according to your needs, you may choose one of the following Playground sample codes in order to solve your problem.使用 Swift 5,您可以根据需要,选择以下 Playground 示例代码之一来解决您的问题。


Turning an array of Character s into a String with no separator:Character数组转换为没有分隔符的String

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

print(string)
// prints "John"

Turning an array of String s into a String with no separator:String数组转换为没有分隔符的String

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

print(string) // prints: "BobDanBryan"

Turning an array of String s into a String with a separator between words:将一个String数组转换为一个String ,单词之间有一个分隔符:

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

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

Turning an array of String s into a String with a separator between characters:String数组转换为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"

Turning an array of Float s into a String with a separator between numbers: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"

Swift 2.0 Xcode 7.0 beta 6 onwards uses joinWithSeparator() instead of join() : Swift 2.0 Xcode 7.0 beta 6 以后使用joinWithSeparator()而不是join()

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

joinWithSeparator is defined as an extension on SequenceType 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
}

斯威夫特 3

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

Since no one has mentioned reduce, here it is:由于没有人提到减少,这里是:

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

In the spirit of functional programming 🤖本着函数式编程的精神🤖

In Swift 4在斯威夫特 4

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

array.joined(separator: " ")

To change an array of Optional/Non-Optional Strings更改可选/非可选字符串数组

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

Here flatMap , compactMap skips the nil values in the array and appends the other values to give a joined string.这里flatMapcompactMap跳过数组中的 nil 值并附加其他值以提供连接的字符串。

Mine works on NSMutableArray with componentsJoinedByString我的 NSMutableArray 与 componentsJoinedByString 一起工作

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

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

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

Result will be >>> Mani Singh iOS Developer结果将是 >>> Mani Singh iOS Developer

If you want to ditch empty strings in the array.如果你想丢弃数组中的空字符串。

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

If you want to filter nil values as well:如果您还想过滤 nil 值:

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

if you want convert custom object array to string or comma separated string (csv) you can use如果您想将自定义 object 数组转换为字符串或逗号分隔字符串 (csv),您可以使用

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

credit to: urvish modi post: Convert an array of Ints to a comma separated string归功于: urvish modi post: 将 Ints 数组转换为逗号分隔的字符串

Nowadays, in iOS 13+ and macOS 10.15+, we might use ListFormatter :如今,在 iOS 13+ 和 macOS 10.15+ 中,我们可能会使用ListFormatter

let formatter = ListFormatter()

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

That will produce a nice, natural language string representation of the list.这将产生一个漂亮的、自然语言的列表字符串表示。 A US user will see:美国用户将看到:

Moe, Larry, and Curly萌、拉里和卷毛

It will support any languages for which (a) your app has been localized;它将支持 (a) 您的应用已本地化的任何语言; and (b) the user's device is configured. (b) 用户的设备已配置。 For example, a German user with an app supporting German localization, would see:例如,使用支持德语本地化的应用程序的德国用户将看到:

Moe, Larry und Curly萌、拉里和卷毛

The Swift equivalent to what you're describing is string interpolation.与您所描述的 Swift 等效的是字符串插值。 If you're thinking about things like JavaScript doing "x" + array , the equivalent in Swift is "x\\(array)" .如果你正在考虑 JavaScript 做"x" + array类的事情,那么 Swift 中的等价物是"x\\(array)"

As a general note, there is an important difference between string interpolation vs the Printable protocol.作为一般说明,字符串插值与Printable协议之间存在重要区别。 Only certain classes conform to Printable .只有某些类符合Printable Every class can be string interpolated somehow.每个类都可以以某种方式进行字符串插值。 That's helpful when writing generic functions.这在编写泛型函数时很有帮助。 You don't have to limit yourself to Printable classes.您不必将自己限制在Printable类上。

You can print any object using the print function您可以使用打印功能打印任何对象

or use \\(name) to convert any object to a string.或使用\\(name)将任何对象转换为字符串。

Example:例子:

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]"

Create extension for an Array :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
        }
    }
}

A separator can be a bad idea for some languages like Hebrew or Japanese.对于希伯来语或日语等某些语言,分隔符可能不是一个好主意。 Try this:尝试这个:

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

For other data types respectively:分别对于其他数据类型:

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

if you have string array list , then convert to Int如果您有字符串数组 list ,则转换为 Int

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

it will give you string value它会给你字符串值

for any Element type对于任何元素类型

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

Try This:尝试这个:

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

use this when you want to convert list of struct type into string当您想将结构类型列表转换为字符串时使用它

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

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

and covert your array like this way并像这样隐藏你的阵列

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

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

you can use joined() to get a single String when you have array of struct also.当您也有结构数组时,您可以使用joined()来获取单个字符串

struct Person{
    let name:String
    let contact:String
}

You can easily produce string using map() & joined()您可以使用map()joined()轻松生成字符串

PersonList.map({"\($0.name) - \($0.contact)"}).joined(separator: " | ")

output:输出:

Jhon - 123 | Mark - 456 | Ben - 789  

You can either use loops for getting this done.您可以使用循环来完成此操作。 Or by using map.或使用 map。

By mapping:通过映射:

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

so in separator you can modify the string.所以在分隔符中你可以修改字符串。

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

FOR SWIFT 3:对于 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
    }
}

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

String(tobeFormattedString)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM