Home > Software design >  Can I turn a list or dictionary to a String list in swift?
Can I turn a list or dictionary to a String list in swift?

Time:08-30

List to String

I want to make something like there’s a list [123] and I want it to be "[123]" using code in Swift. Do you have any idea?

My tries:

Attempt One

String([123]) // error: expression not clear because of not enough content

Attempt Two

[123] as! String // error: unknown error

Dictionary to String

I have a dict like ["123":["123:"123"]] and I want it to be string, like this: "["123":["123":"123"]]"

Dictionary Type: Dictionary<String, Dictionary<String, String>>

I tried using

  • String() initializer
  • as! String!
  • as! String
  • as? String?

But these don't work.

I will thank you very much if your answer is helpful :D

CodePudding user response:

You can achieve it easily with joined() method. First, you will also need to map your array elements to string.

print("["   [123].map(String.init).joined()   "]")
// prints "[123]"

And with more items in the array:

print("["   [1, 2, 3].map(String.init).joined(separator: ", ")   "]")
// prints "[1, 2, 3]"

You can customise the output to your needs with separator parameter.

print("["   [1, 2, 3].map(String.init).joined(separator: "")   "]")
// prints "[123]"

Additional Resources:

Dictionaries Question:

Here is a solution for your dictionary problem, with this code you should be able to modify it to your needs.

extension String {
    var wrappedInBrackets: String { "["   self   "]" }
}

extension Dictionary where Key == String, Value == String {
    var formatted: String {
        map { $0.key   ": "   $0.value }
            .joined(separator: ", ")
            .wrappedInBrackets
    }
}

extension Dictionary where Key == String, Value == [String: String] {
    var formatted: String {
        map { $0.key   ": "   $0.value.formatted }
            .joined(separator: ", ")
            .wrappedInBrackets
    }
}

print(["a": ["b": "c"]].formatted)
// prints "[a: [b: c]]"

CodePudding user response:

Witek's answer is good, and gives you lots of control over the output.

For completeness, another option is the String(describing:) function. In the case of an array of Ints, it gives the same output:

let array = [1, 2, 3]
print(String(describing: array))

That outputs

[1, 2, 3]

Edit:

String(describing:) also works for dictionaries.

This code:

let dictionary = [1: "woof", 2: "snort", 3: "Grunt"]
print(String(describing:dictionary))

Outputs:

[2: "snort", 3: "Grunt", 1: "woof"]

(Dictionaries are unordered, so the output does not preserve the order of the original input.)

  • Related