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() 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:
ListFormatterin Apple Documentation- "Formatter" from NSHipster Blog, section on ListFormatter.
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]]"