Why can't use Character() to convert a string into a charArray

I was doing String related questions on leetcode and found that I have to use a for-loop to iterate through the string and append each char to a new charArray

And Int() can only convert string but not character

var num = 666666
var numArray = [Character]()
String(num).forEach {numArray.append($0)}

that's how I convert a string to a charArray, is the creation of a new array during conversion inevitable?

Why can’t use Character() to convert a string into a charArray

I’m afraid the question isn’t very clear.

// This initializer does not exist.
let aCharacter = Character()
// The apparent intent would be to initialize a null‐ish character.

// Compare these initializers which do exist:
let zero = Int() // i.e. 0
let emptyString = String() // i.e. “”
let string = "Hello, world!"
let characterArray = [Character](string)

Or, if using a for‐loop was the point of the exercise:

let string = "Hello, world!"
var characterArray: [Character] = []

for character in string {
  characterArray.append(character)
}

Int.init(_:) parses the string using the Arabic‐Indic digit system.

let oneHundredTwentyThree = Int("123")!
1 Like

This line solves my problem, thanks

It's more clearly expressed as Array(string). This is calling this overload of Array.init(_:).

It works because String conforms to Sequence (indirectly, it conforms to BidirectionalCollection, which conforms to Collection, which conforms to Sequence), whose Element type is Character.

2 Likes