How do I convert a Swift Array to a String?

IosArraysSwift

Ios Problem Overview


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 Solutions


Solution 1 - Ios

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

var array = ["1", "2", "3"]

let stringRepresentation = "-".join(array) // "1-2-3"

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

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

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

In Swift 3

  • join becomes joined, example [nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator becomes joined(separator:) (only available to Array of Strings)

In Swift 4

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

Solution 2 - Ios

With Swift 5, according to your needs, you may choose one of the following Playground sample codes in order to solve your problem.


Turning an array of Characters into a String with no separator:
let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)

print(string)
// prints "John"

Turning an array of Strings into a String with no separator:
let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")

print(string) // prints: "BobDanBryan"

Turning an array of Strings into a String with a separator between words:
let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")

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

Turning an array of Strings into a String with a separator between characters:
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"

Turning an array of Floats into a String with a separator between numbers:
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"

Solution 3 - Ios

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
}

Solution 4 - Ios

Swift 3

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

Solution 5 - Ios

Since no one has mentioned reduce, here it is:
[0, 1, 1, 0].map {"\($0)"}.reduce("") { $0 + $1 } // "0110"

In the spirit of functional programming 烙

Solution 6 - Ios

In Swift 4

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

array.joined(separator: " ")

Solution 7 - Ios

To change an array of Optional/Non-Optional Strings

//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)

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

Solution 8 - Ios

Nowadays, in iOS 13+ and macOS 10.15+, we might use ListFormatter:

let formatter = ListFormatter()

let names = ["Moe", "Larry", "Curly"]
if let string = formatter.string(from: names) {
    print(string)
}

That will produce a nice, natural language string representation of the list. A US user will see:

> Moe, Larry, and Curly

It will support any languages for which (a) your app has been localized; and (b) the user’s device is configured. For example, a German user with an app supporting German localization, would see:

> Moe, Larry und Curly

Solution 9 - Ios

Mine works on NSMutableArray with componentsJoinedByString

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

Solution 10 - Ios

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

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

Solution 11 - Ios

let arrayTemp :[String] = ["Mani","Singh","iOS Developer"]
    let stringAfterCombining = arrayTemp.componentsJoinedByString(" ")
   print("Result will be >>>  \(stringAfterCombining)")

Result will be >>> Mani Singh iOS Developer

Solution 12 - Ios

If you want to ditch empty strings in the array.

["Jet", "Fire"].filter { !$0.isEmpty }.joined(separator: "-")

If you want to filter nil values as well:

["Jet", nil, "", "Fire"].flatMap { $0 }.filter { !$0.isEmpty }.joined(separator: "-")

Solution 13 - Ios

if you want convert custom object array to string or comma separated string (csv) you can use

 var stringIds = (self.mylist.map{$0.id ?? 0}).map{String($0)}.joined(separator: ",")

credit to : urvish modi post: https://stackoverflow.com/questions/43774352/convert-an-array-of-ints-to-a-comma-separated-string

Solution 14 - Ios

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.

Solution 15 - Ios

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

Solution 16 - Ios

Create extension for an 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
        }
    }
}

Solution 17 - Ios

A separator can be a bad idea for some languages like Hebrew or Japanese. Try this:

// 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!)

For other data types respectively:

// 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!)

Solution 18 - Ios

you can use joined() to get a single String when you have array of struct also.

struct Person{
    let name:String
    let contact:String
}

You can easily produce string using map() & joined()

PersonList.map({"\($0.name) - \($0.contact)"}).joined(separator: " | ")

output:

Jhon - 123 | Mark - 456 | Ben - 789  

Solution 19 - Ios

if you have string array list , then convert to Int

let arrayList = list.map { Int($0)!} 
     arrayList.description

it will give you string value

Solution 20 - Ios

for any Element type

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;
    }
}

Solution 21 - Ios

Try This:

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: ",")

Solution 22 - Ios

use this when you want to convert list of struct type into string

struct MyStruct {
  var name : String
  var content : String
}

let myStructList = [MyStruct(name: "name1" , content: "content1") , MyStruct(name: "name2" , content: "content2")]

and covert your array like this way

let myString = myStructList.map({$0.name}).joined(separator: ",")

will produce ===> "name1,name2"

Solution 23 - Ios

FOR 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
    }
}

Solution 24 - Ios

If you question is something like this: tobeFormattedString = ["a", "b", "c"] Output = "abc"

String(tobeFormattedString)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTroyView Question on Stackoverflow
Solution 1 - IosAntonioView Answer on Stackoverflow
Solution 2 - IosImanou PetitView Answer on Stackoverflow
Solution 3 - IosSivaView Answer on Stackoverflow
Solution 4 - IoshardikdeviosView Answer on Stackoverflow
Solution 5 - IosSentry.coView Answer on Stackoverflow
Solution 6 - IosgargView Answer on Stackoverflow
Solution 7 - IosAgent SmithView Answer on Stackoverflow
Solution 8 - IosRobView Answer on Stackoverflow
Solution 9 - IosOnur VarView Answer on Stackoverflow
Solution 10 - IosCarlos Perez PerezView Answer on Stackoverflow
Solution 11 - IosManinderjit SinghView Answer on Stackoverflow
Solution 12 - IosSourav ChandraView Answer on Stackoverflow
Solution 13 - Ioskrishnamurthy View Answer on Stackoverflow
Solution 14 - IosRob NapierView Answer on Stackoverflow
Solution 15 - Ios123FLO321View Answer on Stackoverflow
Solution 16 - IosBartłomiej SemańczykView Answer on Stackoverflow
Solution 17 - IosAlexey ChekanovView Answer on Stackoverflow
Solution 18 - IosDilanView Answer on Stackoverflow
Solution 19 - IosOshitha WimalasuriyaView Answer on Stackoverflow
Solution 20 - Iosjohn07View Answer on Stackoverflow
Solution 21 - IosTej PatelView Answer on Stackoverflow
Solution 22 - Ioselhoucine ayoubView Answer on Stackoverflow
Solution 23 - IosTy DanielsView Answer on Stackoverflow
Solution 24 - IosdheeruView Answer on Stackoverflow