Swift Group Separator
An example about Swift Group Separator. Long numbers can be a bit confusing to read if they dont contain group separator. By default you dont have that option in Swift. But it is quite easy to add your self. And if you add group separator as an extension you can reuse it easily.
In this example I will show you how to add group separator extension to Int. You can do this to other numbers to, not just integers.
You want to add extensions outside of any class. So put it outside the brackets in one of the swift files, or create a new swift file this extensions. I often create a util.swift file in my projects.
Here is the swift group separator code:
extension Int {
var addSeparator: String {
let nf = NSNumberFormatter()
nf.groupingSeparator = " "
nf.numberStyle = NSNumberFormatterStyle.DecimalStyle
return nf.stringFromNumber(self)!
}
}
So if this is your existing code, you will not have group separators in your numbers.
let myNumber = 10000
print"\(myNumber)"
Your output will just be:
10000
Now if you want to use this swift group separator extension, simply change it to this:
let myNumber = 10000
print"\(myNumber.addSeparator)"
And your output will be:
10,000
You can of course change your extension code to use other group separators than a comma. You can use what ever you want.
If you want to see this code in action, you can go to my YouTube video
https://www.youtube.com/watch?v=021DyjmR_0Q
Or press play below
Or you can download some example code from my github account. Click the link to go to this extension directly: https://github.com/solron/GroupSeparatorExtension
That is it really on how to do swift group separator extensions.
My github account: https://github.com/solron
My YouTube account: https://www.youtube.com/user/solron75/videos
Happy grouping!