The output of the [Character] Array currently is:
["E", "x", "a", "m", "p", "l", "e"]
It should be:
Example
It could be that "
is in the array, like this: """
. That output should be "
.
Thank you!
To convert an array to string in Swift, call Array. joined() function.
that is the way to get a nice unicode character array in Swfit: var charArray: Array<Character> = Array(count: 100, repeatedValue: "?")
To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.
The other answer(s) cover the case where your array is one of String
elements (which is most likely the case here: since you haven't supplied us the type of the array, we could use Swift own type inference rules to speculatively infer the type to be [String]
).
In case the elements of your array are in fact of type Character
, however, you could use the Character
sequence initializer of String
directly:
let charArr: [Character] = ["E", "x", "a", "m", "p", "l", "e"] let str = String(charArr) // Example
W.r.t. your comment below: if your example array is, for some reason, one of Any
elements (which is generally not a good idea to use explicitly, but sometimes the case when recieving data from some external source), you first need to perform an attempted conversion of each Any
element to String
type, prior to concenating the converted elements to a single String
instance. After the conversion, you will be working with an array of String
elements, in which case the methods shown in the other answers will be the appropriate method of concenation:
// e.g. using joined() let arr: [Any] = ["E", "x", "a", "m", "p", "l", "e"] let str = arr.flatMap { $0 as? String }.joined() print(str) // example
You could naturally also (attempt to) convert from Any
to Character
elements, but even in this case you would have to go via String
instances, which means that for the [Any]
case, the joined()
alternative above is to prefer over the one below:
let arr: [Any] = ["E", "x", "a", "m", "p", "l", "e"] let str = String(arr.flatMap { ($0 as? String)?.characters.first }) print(str) // example
Just use joined()
with default ""
separator:
let joinedString = ["E", "x", "a", "m", "p", "l", "e"].joined()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With