Skip to content

Instantly share code, notes, and snippets.

@theevo
Last active May 2, 2020 21:21
Show Gist options
  • Save theevo/e8afe9408bc85f10006980484d83d82d to your computer and use it in GitHub Desktop.
Save theevo/e8afe9408bc85f10006980484d83d82d to your computer and use it in GitHub Desktop.
converting integers to strings in Swift
import Foundation
// a coding exercise from repl.it motivated me to learn how to convert numbers (specifically integers) into strings
// In part 1, I explored the different ways to convert an integer simply to a string. so if you're given the int 9, you should output the string literal "9"
// several solutions were put forth from https://stackoverflow.com/questions/24161336/convert-int-to-string-in-swift
var x: Int = 9
var s = String(x) // this one makes the most sense to me
var ss = "\(x)"
//var sss = toString(x) // doesn't work. maybe deprecated?
var ssss = x.description // one dev said it worked when showing the value in a label.
var sssss: String = String(describing: x)
// In part 2, I looked into spelling out a number in English. Given the integer 5, output the string "five".
// In Swift, we can make use of NumberFormatter to help us. This would be terribly daunting (or usefully challenging) to write on our own.
// useful documentation: https://nshipster.com/formatter/#numberformatter
let numFormatter = NumberFormatter() // it's a constant. it does not work as a variable.
numFormatter.numberStyle = .spellOut
var fiveAsNSNumber = numFormatter.number(from: "five") // 5
numFormatter.numberStyle = .spellOut
var numberSpelledOut = numFormatter.string(from: NSNumber(value: x)) // "nine"
numberSpelledOut = numFormatter.string(from: NSNumber(value: 1024)) // "one thousand twenty-four"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment