amagain
amagain

Reputation: 2072

Mapping Integer to String in Swift

What is the easiest way to map an Integer to a String? Here's an array of Integer.

let englishIntLiterals: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

I want to map the occurrences of each digits to their Nepali equivalent numbers, which is represented as an array of Strings.

let nepaliLiterals: [String] = ["१", "२", "३", "४", "५", "६", "७", "८", "९", "०"]

I need 1 to be replaced by and so on. I know there is a work around with functions, but I am looking after a higher order function solution, which I have not been able to figure out with.

Upvotes: 1

Views: 1289

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236420

You can use a fixed locale number formatter to display your integer localized:

extension Formatter {
    static let numberNepal: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.locale = Locale(identifier: "ne_NP")
        formatter.numberStyle = .decimal
        return formatter
    }()
}
extension BinaryInteger {
    var nepaliFormatted: String {
        return Formatter.numberNepal.string(for: self)!
    }
}

1234567890.nepaliFormatted  // "१,२३४,५६७,८९०"

let englishIntLiterals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

let nepaliLiterals = englishIntLiterals.map{$0.nepaliFormatted}  // "१", "२", "३", "४", "५", "६", "७", "८", "९", "०"]

Upvotes: 4

Sahil Manchanda
Sahil Manchanda

Reputation: 10012

Try the following. I've made a small extension which should do the job that you are looking for. I extend its capability to entertain large as well as negative numbers also.

extension Int{

    func toNepali() -> String{
        let isNegative = self < 0
        let number = abs(self)
        let nepaliLiterals: [String] = [ "०","१", "२", "३", "४", "५", "६", "७", "८", "९"]
        if number > 9{
            var s = isNegative ?  "-" : ""
            for i in "\(number)"{
                s += "\(nepaliLiterals[Int(String(i))!])"
            }
            return  s
        }else{
            return isNegative ? "-\(nepaliLiterals[number])" : nepaliLiterals[number]        
        }
    }
}

Test:

let englishIntLiterals: [Int] = [-10,0,1,2,3,4,5,6,7,8,9,100]
for i in englishIntLiterals{
    print(i.toNepali())
}

Output:

-१०
०
१
२
३
४
५
६
७
८
९
१००

Upvotes: 0

Related Questions