如何将Swift数组转换为string?

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

我使用过的每种语言都有一些默认的文本表示forms,当你试图连接一个string或者将它传递给一个print()函数等等时,它会吐出来。Apple的Swift语言有一个很容易把数组转换成string的内置方式,或者当把数组string化时,我们总是必须是显式的?

如果数组包含string,则可以使用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" 

如果你想使用特定的分隔符(hypen,空白,逗号等),这会很有用。

否则,您可以简单地使用description属性,它返回数组的string表示forms:

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

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

Swift 3

  • join成为joined ,例如[nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator成为joined(separator:) (仅适用于string数组)

使用Swift 3,根据您的需要,您可以select以下代码块之一。


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

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

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

 let stringArray = ["Foo", "Bar", "Baz"] let characterArray = stringArray.flatMap { String.CharacterView($0) } //let characterArray = stringArray.flatMap { $0.characters } // also works let string = String(characterArray) print(string) // prints "FooBarBaz" 

String数组转换为String间的分隔符的String

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

使用字符之间的分隔符将String数组转换为String

 let stringArray = ["car", "bike", "boat"] let stringArray2 = stringArray.flatMap { String.CharacterView($0) }.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.flatMap { String($0) } let string = stringArray.joined(separator: "-") print(string) // prints "12.0-14.6-35.0" 

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 } 

Swift 3

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

我的工作与componentsJoinedByString NSMutableArray

 var array = ["1", "2", "3"] let stringRepresentation = array.componentsJoinedByString("-") // "1-2-3" 
 let arrayTemp :[String] = ["Mani","Singh","iOS Developer"] let stringAfterCombining = arrayTemp.componentsJoinedByString(" ") print("Result will be >>> \(stringAfterCombining)") 

结果将是>>> Mani Singh iOS Developer

在Swift 2.2中,你可能不得不把你的数组转换成NSArray来使用componentsJoinedByString(“,”)

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

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

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

本着函数式编程的精神

Swift相当于你所描述的是string插值。 如果你正在考虑像JavaScript这样的"x" + array ,那么Swift中的等价物就是"x\(array)"

作为一般说明,string插值与Printable协议之间有一个重要区别。 只有某些类符合Printable每个类都可以以某种方式插入string。 这在编写generics函数时很有用。 您不必限制自己Printable类。

您可以使用打印function打印任何对象

或使用\(name)将任何对象转换为string。

例:

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

更改可选/非可选string的数组

 //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) print(joinedString) 

这里flatMap会跳过数组中的nil值并附加其他的值来给出一个连接string。

Array创build扩展:

 extension Array { var string: String? { do { let data = try JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted]) return String(data: data, encoding: .utf8) } catch { return nil } } } 

在斯威夫特4

 let array:[String] = ["Apple", "Pear ","Orange"] array.joined(separator: " ") 

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