Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I turn a list or dictionary to a String list in swift?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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() method
  • as! String!
  • as! String
  • as? String?

But these dont work, pls helppppppp

I will thank you very much if your answer is helpful 😀

>Solution :

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]]"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading