我知道如何以编程方式做到这一点,但是我敢肯定有一种内置的方式...
我使用的每种语言都有一组对象的默认文本表示形式,当您尝试将Array与字符串连接起来或将其传递给print()函数时,它会吐出。Apple的Swift语言是否可以有一种轻松地将数组转换为字符串的内置方法,还是在对数组进行字符串化时始终必须明确?
我知道如何以编程方式做到这一点,但是我敢肯定有一种内置的方式...
我使用的每种语言都有一组对象的默认文本表示形式,当您尝试将Array与字符串连接起来或将其传递给print()函数时,它会吐出。Apple的Swift语言是否可以有一种轻松地将数组转换为字符串的内置方法,还是在对数组进行字符串化时始终必须明确?
Answers:
如果数组包含字符串,则可以使用String
的join
方法:
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:"-")
"-".join(array)
在Swift 2,Xcode 7 Beta 6中不再可用,请尝试使用array.joinWithSeparator("-")
joinWithSeparator
仅适用于字符串数组。如果您有其他对象数组,map
请先使用。例如,[1, 2, 3].map({"\($0)"}).joinWithSeparator(",")
使用Swift 5,您可以根据需要选择以下Playground示例代码之一来解决您的问题。
Character
s 数组转换为String
不带分隔符的:let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)
print(string)
// prints "John"
String
s 数组转换为String
不带分隔符的:let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")
print(string) // prints: "BobDanBryan"
String
s 数组变成a String
,并在单词之间使用分隔符:let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")
print(string) // prints: "Bob Dan Bryan"
String
s 数组转换为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"
Float
s 数组转换为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"
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(" ")
更改可选/非可选字符串的数组
//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值,并附加其他值以提供连接的字符串。
在Swift 2.2中,您可能必须将数组转换为NSArray才能使用componentsJoinedByString(“,”)
let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")
如果要抛空数组中的空字符串。
["Jet", "Fire"].filter { !$0.isEmpty }.joined(separator: "-")
如果还要过滤nil值:
["Jet", nil, "", "Fire"].flatMap { $0 }.filter { !$0.isEmpty }.joined(separator: "-")
let arrayTemp :[String] = ["Mani","Singh","iOS Developer"]
let stringAfterCombining = arrayTemp.componentsJoinedByString(" ")
print("Result will be >>> \(stringAfterCombining)")
结果将是>>> Mani Singh iOS Developer
为创建扩展名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!)
如果您有字符串数组列表,则转换为Int
let arrayList = list.map { Int($0)!}
arrayList.description
它会给你字符串值
尝试这个:
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: ",")
对于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
}
}
array.description
或者如果您需要自定义分隔符array.joined(separator: ",")