-
-
Save mingsai/c2c29ae36ec20c3cdd3f to your computer and use it in GitHub Desktop.
Abizern's NSNumberFormatter subclass translated into Swift - http://stackoverflow.com/questions/3312935/nsnumberformatter-and-th-st-nd-rd-ordinal-number-endings/3316016#3316016
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// OrdinalNumberFormatter.swift | |
// Tastify | |
// | |
// Created by Ian Grossberg on 10/1/15. | |
// Copyright © 2015 Noble Desktop. All rights reserved. | |
// | |
import Foundation | |
import CocoaLumberjack | |
// translated from http://stackoverflow.com/a/3316016 | |
class OrdinalNumberFormatter: NSNumberFormatter { | |
override func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool { | |
var integerNumber : Int = 0 | |
var isSuccessful = false | |
let scanner = NSScanner(string: string) | |
scanner.caseSensitive = false | |
scanner.charactersToBeSkipped = NSCharacterSet.letterCharacterSet() | |
if scanner.scanInteger(&integerNumber) == true | |
{ | |
isSuccessful = true | |
obj.memory = NSNumber(integer: integerNumber) | |
} else | |
{ | |
if let error = error.memory | |
{ | |
DDLog.error("Unable to create number from \(string): \(error)") | |
} | |
} | |
return isSuccessful | |
} | |
override func stringForObjectValue(obj: AnyObject) -> String? { | |
if !obj.isKindOfClass(NSNumber.self) | |
{ | |
return nil | |
} | |
var result : String? | |
if let stringRepresentation = obj.stringValue | |
{ | |
if stringRepresentation.characters.count > 0 | |
{ | |
var ordinal : String? | |
if stringRepresentation == "11" || stringRepresentation == "12" || stringRepresentation == "13" | |
{ | |
ordinal = "th" | |
} else if let lastDigit = stringRepresentation.characters.last | |
{ | |
ordinal = OrdinalNumberFormatter.ordinalSuffixForLastDigit(lastDigit) | |
} | |
if let ordinal = ordinal | |
{ | |
result = "\(stringRepresentation)\(ordinal)" | |
} | |
} | |
} | |
return result | |
} | |
class func ordinalSuffixForLastDigit(digit : Character) -> String? { | |
var result : String? | |
if digit == "1" | |
{ | |
result = "st" | |
} else if digit == "2" | |
{ | |
result = "nd" | |
} else if digit == "3" | |
{ | |
result = "rd" | |
} else | |
{ | |
result = "th" | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment