如果数组包含字符串,您可以使用 String
的 join
方法:
var array = ["1", "2", "3"]
let stringRepresentation = "-".join(array) // "1-2-3"
在斯威夫特 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
属性。如果您在自己的类/结构中采用该协议,您也可以使它们打印友好
在斯威夫特 3
join 变为joined,例如 [nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator 变为joined(separator:) (仅适用于字符串数组)
在斯威夫特 4
var array = ["1", "2", "3"]
array.joined(separator:"-")
使用 Swift 5,根据您的需要,您可以选择以下 Playground 示例代码之一来解决您的问题。
将字符数组转换为不带分隔符的字符串:
let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)
print(string)
// prints "John"
将字符串数组转换为不带分隔符的字符串:
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"
将浮点数组转换为字符串,数字之间有分隔符:
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"
try JSONDecoder().decode([Int].self, from: Data(string.utf8))
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
}
斯威夫特 3
["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")
由于没有人提到reduce,这里是:
[0, 1, 1, 0].map {"\($0)"}.reduce("") { $0 + $1 } // "0110"
本着函数式编程的精神🤖
[0,1,1,0].map{"\($0)"}.reduce("",+)
。 😉
[0,1,1,0].map(String.init).joined()
在斯威夫特 4
let array:[String] = ["Apple", "Pear ","Orange"]
array.joined(separator: " ")
更改可选/非可选字符串数组
//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 值并附加其他值以提供连接的字符串。
如今,在 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) 配置用户的设备。例如,使用支持德语本地化的应用程序的德国用户会看到:
萌,拉里和卷毛
我的作品在 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)")
结果将是 >>> Mani Singh iOS 开发人员
如果要丢弃数组中的空字符串。
["Jet", "Fire"].filter { !$0.isEmpty }.joined(separator: "-")
如果您还想过滤 nil 值:
["Jet", nil, "", "Fire"].flatMap { $0 }.filter { !$0.isEmpty }.joined(separator: "-")
如果您想将自定义对象数组转换为字符串或逗号分隔的字符串 (csv),您可以使用
var stringIds = (self.mylist.map{$0.id ?? 0}).map{String($0)}.joined(separator: ",")
归功于:urvish modi 帖子:Convert an array of Ints to a comma separated string
与您所描述的 Swift 等效的是字符串插值。如果您正在考虑诸如 JavaScript 执行 "x" + array
之类的事情,那么 Swift 中的等价物是 "x\(array)"
。
作为一般说明,字符串插值与 Printable
协议之间存在重要区别。只有某些类符合 Printable
。 Every 类可以以某种方式进行字符串插值。这在编写泛型函数时很有帮助。您不必将自己限制在 Printable
个课程中。
您可以使用打印功能打印任何对象
或使用 \(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]"
为 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
}
}
}
对于希伯来语或日语等某些语言,分隔符可能不是一个好主意。尝试这个:
// 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!)
当您也有结构数组时,您可以使用 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
如果您有字符串数组列表,则转换为 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"
对于斯威夫特 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)
String
没有能够做到这一点的初始化程序。要么您使用的是自定义扩展或第三方库,要么您完全弄错了。
"-".join(array)
在 Swift 2、Xcode 7 Beta 6 中不再可用,请尝试使用array.joinWithSeparator("-")
joinWithSeparator
仅适用于字符串数组。如果您有其他对象数组,请先使用map
。例如,[1, 2, 3].map({"\($0)"}).joinWithSeparator(",")