Skeleton Bow
Skeleton Bow

Reputation: 529

Convert string into array without quotation marks in Swift 3

My question:

This answer explains how to convert a String containing elements separated by spaces into an array.

let numbers = "1 2 3 4"
let numbersArray = numbers.components(separatedBy: " ")
print(numbersArray)
// output: ["1", "2", "3", "4"]
// but I want: [1, 2, 3, 4]

However, I'm trying to make an array without quotation marks, because I'm making an array of numbers, not strings.

My attempts:

I tried removing all quotation marks from numbersArray, but this didn't work as it's an array, not a string.

numbersArray.replacingOccurrences(of: "\"", with: "") // won't work

I tried something different: I tried adding each element in the array to a new array, hoping that new array wouldn't contain quotation marks. I got an error, though:

let numbers = "1 2 3 4" // string to be converted into array without quotes
let numbersArray = numbers.components(separatedBy: " ") // convert string into array with quotes
var newNumbersArray = [String]() // new blank array (which will be without quotes)
for i in numbersArray { // for each item in the array with quotes
  newNumbersArray += i // (hopefully) add the item in the new array without quotes
} 
print(newNumbersArray) // print the new array 

This gives me an error:

Swift:: Error: cannot convert value of type '[String]' to expected argument type 'inout String'
  newNumbersArray += i

Upvotes: 1

Views: 1422

Answers (3)

Jaydeep Vora
Jaydeep Vora

Reputation: 6223

Swift 3.0

Try this.. Chaining method makes it easy.

let temp = "1 2 3 4 5 6"
var numbers: [Int] = []

temp.components(separatedBy: " ").forEach { numbers.append(Int($0)!) }

print(numbers) //[1, 2, 3, 4, 5, 6]

Upvotes: 1

dfrib
dfrib

Reputation: 73236

You can apply a flatMap call on the [String] array resulting from the call to components(separatedBy:), applying the failable init(_:radix:) of Int in the body of the transform closure of the flatMap invokation:

let strNumbers = "1 2 3 4"
let numbersArray = strNumbers
    .components(separatedBy: " ")
    .flatMap { Int($0) }

print(numbersArray) // [1, 2, 3, 4]
print(type(of: numbersArray)) // Array<Int>

Upvotes: 2

Phyber
Phyber

Reputation: 1368

You can try this:

var newArray = [Int]()

for item in numbersArray{
    newArray.append(Int(item))
}

print(newArray)

Upvotes: 1

Related Questions