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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25827033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:26:05  来源:igfitidea点击:

How do I convert a Swift Array to a String?

iosarraysswift

提问by Troy

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?

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

回答by Antonio

If the array contains strings, you can use the String's joinmethod:

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

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 descriptionproperty, which returns a string representation of the array:

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

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

Hint: any object implementing the Printableprotocol has a descriptionproperty. If you adopt that protocol in your own classes/structs, you make them print friendly as well

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

In Swift 3

斯威夫特 3

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

In Swift 4

斯威夫特 4

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

回答by Imanou Petit

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 Characters into a Stringwith no separator:

将一个Characters数组转换为一个String没有分隔符的数组:

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

print(string)
// prints "John"


Turning an array of Strings into a Stringwith no separator:

将一个Strings数组转换为一个String没有分隔符的数组:

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

print(string) // prints: "BobDanBryan"


Turning an array of Strings into a Stringwith a separator between words:

将一个Strings数组转换为一个String单词之间的分隔符:

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

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


Turning an array of Strings into a Stringwith a separator between characters:

将一个Strings数组转换为一个String字符之间的分隔符:

let stringArray = ["car", "bike", "boat"]
let characterArray = stringArray.flatMap { 
let floatArray = [12, 14.6, 35]
let stringArray = floatArray.map { String(
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
) } let string = stringArray.joined(separator: "-") print(string) // prints "12.0-14.6-35.0"
} let stringArray2 = characterArray.map { String(
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
}
) } let string = stringArray2.joined(separator: ", ") print(string) // prints: "c, a, r, b, i, k, e, b, o, a, t"


Turning an array of Floats into a Stringwith a separator between numbers:

将一个Floats数组转换为一个String数字之间的分隔符:

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

回答by Siva

Swift 2.0 Xcode 7.0 beta 6 onwards uses joinWithSeparator()instead of join():

Swift 2.0 Xcode 7.0 beta 6 以后使用joinWithSeparator()而不是join()

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

array.joined(separator: " ")

joinWithSeparatoris defined as an extension on SequenceType

joinWithSeparator被定义为扩展 SequenceType

[0, 1, 1, 0].map {"\(
//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{ 
var array = ["1", "2", "3"]
let stringRepresentation = array.componentsJoinedByString("-") // "1-2-3"
}.joined(separator: separator) //Use Compact map in case of **Swift 4** let joinedString = array.compactMap{
let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")
}.joined(separator: separator print(joinedString)
)"}.reduce("") {
["Jet", "Fire"].filter { !
["Jet", nil, "", "Fire"].flatMap { ##代码## }.filter { !##代码##.isEmpty }.joined(separator: "-")
.isEmpty }.joined(separator: "-")
+ } // "0110"

回答by hardikdevios

Swift 3

斯威夫特 3

##代码##

回答by Ankit garg

In Swift 4

在斯威夫特 4

##代码##

回答by eonist

Since no one has mentioned reduce, here it is:

由于没有人提到减少,这里是:

##代码##

In the spirit of functional programming

本着函数式编程的精神

回答by Agent Smith

To change an array of Optional/Non-Optional Strings

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

##代码##

Here flatMap, compactMapskips the nil values in the array and appends the other values to give a joined string.

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

回答by Onur Var

Mine works on NSMutableArray with componentsJoinedByString

我的 NSMutableArray 与 componentsJoinedByString 一起工作

##代码##

回答by Carlos Perez Perez

In Swift 2.2 you may have to cast your array to NSArray to use componentsJoinedByString(",")

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

##代码##

回答by Sourav Chandra

If you want to ditch empty strings in the array.

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

##代码##

If you want to filter nil values as well:

如果您还想过滤 nil 值:

##代码##