How do I convert a Swift Array to a String?

2019-01-01 10:20发布

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?

标签: ios arrays swift
18条回答
何处买醉
2楼-- · 2019-01-01 10:33
let arrayTemp :[String] = ["Mani","Singh","iOS Developer"]
    let stringAfterCombining = arrayTemp.componentsJoinedByString(" ")
   print("Result will be >>>  \(stringAfterCombining)")

Result will be >>> Mani Singh iOS Developer

查看更多
只靠听说
3楼-- · 2019-01-01 10:33

The Swift equivalent to what you're describing is string interpolation. If you're thinking about things like JavaScript doing "x" + array, the equivalent in Swift is "x\(array)".

As a general note, there is an important difference between string interpolation vs the Printable protocol. Only certain classes conform to 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.

查看更多
像晚风撩人
4楼-- · 2019-01-01 10:35

Swift 3

["I Love","Swift"].joined(separator:" ") // previously joinWithSeparator(" ")
查看更多
爱死公子算了
5楼-- · 2019-01-01 10:38

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

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

joinWithSeparator is defined as an extension on 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
}
查看更多
看风景的人
6楼-- · 2019-01-01 10:38

You can print any object using the print function

or use \(name) to convert any object to a string.

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]"
查看更多
残风、尘缘若梦
7楼-- · 2019-01-01 10:39

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

let stringWithCommas = (yourArray as NSArray).componentsJoinedByString(",")
查看更多
登录 后发表回答