Rob13
Rob13

Reputation: 381

How to convert Characters to Int in Swift 4?

I have readLine() which gives me the character. So, I have this:

223 345 567 and so on. So, when I convert them to Int first thing says these are character so, I researched and found this solution and when I use this:

let size    = readLine()
var array   = [Int]()
let numbers = readLine()

for number in numbers!
{
  if let integer = Int(String(number))
  {
      array.append(integer)
  }
}
print(array)

So, when I am printing the array, I am getting these as [2,2,3,3,4,5,5,6,7] instead of [223,345,567]. Can anyone help?

Here is the extract of new code.

let numbers = readLine()
var array   = [Int]()
guard let numberStrings = numbers?.components(separatedBy: " ") else{
fatalError()
}
for number in numberStrings {
if let validNumber = Int(number) {
    array.append(validNumber)
}
}

print(array)

Upvotes: 0

Views: 2884

Answers (2)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

You need to split the string and find every number string and then convert them to Int.

let numbers = readLine()
var numberArray: [Int] = []
guard let numberStrings = numbers?.components(separatedBy: " ") else {
    fatalError()
}

for number in numberStrings {
    if let validNumber = Int(number) {
        numberArray.append(validNumber)
    }
}

Upvotes: 1

Rizwan
Rizwan

Reputation: 3666

for number in numbers!

This line of code extracts each character in the string (223 345 567) and tries to convert it to int. That's why it converts each valid number in string and left the spaces. You need to first split the string in to array of string numbers then iterate through the array to convert them.

Split it, further iterate through strNumArray and convert them to integers

var array   = [Int]()
if let strNumArray = numbers?.components(separatedBy: " ") {
    for number in strNumArray {
        if let integer = Int(String(number)) {
            array.append(integer)
        }
    }
}
print(array)

And in more swifty way

var arrayInt = numbers.split(separator: " ").map{Int($0)}

Upvotes: 0

Related Questions