I was trying to converting a string into an array of numbers. The string is from a linked list and I want to get the numbers in the string without accessing the actual nodes.
here is my code:
list.append(value: 1)
list.append(value: 80)
list.append(value: 3)
list.append(value: 7)
var numbers = list.description.compactMap{$0.wholeNumberValue}
it outputs :
[1, 8, 0, 3, 7]
I want it to outputs like this:
[1, 80, 3, 7]
But I have no idea how to do it
CodePudding user response:
What you are trying to do is impossible.
list
is a String. So, after you append the numbers it looks like this:
"18037"
There is no way to know that it was originally made from [1, 80, 3, 7]
. It could have been [180, 37]
or [18, 0, 37]
You haven't explained why you want to do this, but I would suggest either
- Not using a string to store the values. In your case, use an
Array<Int>
- If you have to use a string, use a delimiter between the values, so that you end up with
"1,80,3,7"
instead and then you can parse them. (see components(separatedBy:))
CodePudding user response:
Hello Use Only map function to convert Int array to String :----
var list = [Int]()
list.append(1)
list.append(80)
list.append(3)
list.append(7)
var numbersString = list.map { String($0) }
print(numbersString)
Output :--- ["1", "80", "3", "7"]