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
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")!
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
.