Petravd1994
Petravd1994

Reputation: 903

Character Array to string in Swift

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!

Upvotes: 37

Views: 36174

Answers (3)

dfrib
dfrib

Reputation: 73186

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

Upvotes: 76

vadian
vadian

Reputation: 285082

Just use joined() with default "" separator:

let joinedString = ["E", "x", "a", "m", "p", "l", "e"].joined()

Upvotes: 11

Josh Homann
Josh Homann

Reputation: 16327

let e = ["E", "x", "a", "m", "p", "l", "e"]
print(e.reduce ("", +))

Upvotes: 5

Related Questions