I have a number, I want to insert a column ":" between each two consecutive digits inside that number, and get a String as a result
For example:
let number: Int = 34567
let result: String = "3:4:5:6:7"
Thanks for any help,
I have a number, I want to insert a column ":" between each two consecutive digits inside that number, and get a String as a result
For example:
let number: Int = 34567
let result: String = "3:4:5:6:7"
Thanks for any help,
Possible solution:
let result = String(number).map({ String($0) }).joined(separator: ":")
With explanation of intermediary results to help understand what's going on on theses 3 chained methods:
let interemdiary1 = String(number)
print("interemdiary1: \(interemdiary1)")
let interemdiary2 = interemdiary1.map({ String($0 )})
print("interemdiary2: \(interemdiary2)")
let interemdiary3 = interemdiary2.joined(separator: ":")
print("interemdiary3: \(interemdiary3)")
Output:
$>interemdiary1: 34567
$>interemdiary2: ["3", "4", "5", "6", "7"]
$>interemdiary3: 3:4:5:6:7
First, let's transform your number
into a String.
Then, let's create an array of it where each character (as a String
) of the previous result is an element of it. I used a map()
of it.
Finally, we use joined(separator:)
to assemble them.
Another kind of solution can be found there: How add separator to string at every N characters in swift? It's just that you do it each 1 characters.
You need to join it by :
use this
let result = String(number).map({String($0)}).joined(separator: ":")