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:39

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
        }
    }
}
查看更多
千与千寻千般痛.
3楼-- · 2019-01-01 10:40

if you have string array list , then convert to Int

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

it will give you string value

查看更多
笑指拈花
4楼-- · 2019-01-01 10:41

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!)
查看更多
与君花间醉酒
5楼-- · 2019-01-01 10:41

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
    }
}
查看更多
怪性笑人.
6楼-- · 2019-01-01 10:45

With Swift 3, according to your needs, you may choose one of the following blocks of code.


Turning an array of Character 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 String into a String with no separator:

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"

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

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"

Turning an array of Float into a String with a separator between numbers:

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"
查看更多
路过你的时光
7楼-- · 2019-01-01 10:47

Mine works on NSMutableArray with componentsJoinedByString

var array = ["1", "2", "3"]
let stringRepresentation = array.componentsJoinedByString("-") // "1-2-3"
查看更多
登录 后发表回答