Swift Group Separator Extension

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

Your output will just be:

Now if you want to use this swift group separator extension, simply change it to this:

let myNumber = 10000

And your output will be:

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
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!

About Author

Related Posts

C# Reference Types

Understanding C# Reference Types

One of the key features of C# is its support for C# reference types, which allow developers to create complex, object-oriented applications. In this blog post, we…

c# value types

Understanding C# Value Types

C# is a powerful programming language that is widely used for developing a wide range of applications. One of the key features of C# is its support…

C# check if server is online

C# check if server is online directly from your code. Check servers or services like web servers, database servers like MySQL and MongoDB. You can probably check…

C# Convert Int to Char

C# convert int to char google search is giving some result which I think is not directly what some people want. Most results are giving instructions on…

c# bash script

C# Bash Script Made Easy

There are many reasons why it could be handy to run a bash script from a C# application. In 2014, before I changed to a Mac as…

go hello world

Golang Hello World, Get a Easy Fantastic Start

Golang hello world example tutorial. I assume you are new to the golang language since you found this website. Go is one of the latest programming languages…

Leave a Reply