Skip to content

Instantly share code, notes, and snippets.

@volonbolon
Created January 10, 2018 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volonbolon/bf3dd3cb66dc8fd142c6ebfa273974cd to your computer and use it in GitHub Desktop.
Save volonbolon/bf3dd3cb66dc8fd142c6ebfa273974cd to your computer and use it in GitHub Desktop.
String / Int Conversions
//: Playground - noun: a place where people can play
import UIKit
extension Character {
var asciiValue: Int {
get {
let s = String(self).unicodeScalars
return Int(s[s.startIndex].value)
}
}
}
extension String {
var asInt: Int {
let base = Array("0").first!.asciiValue
var result = 0
let negative = self.hasPrefix("-")
let startIndex = negative ? 1 : 0
let stringAsArray = Array(self)
for index in startIndex..<stringAsArray.count {
let c = stringAsArray[index]
let delta = c.asciiValue - base
result *= 10 // Horner's Rule http://mathworld.wolfram.com/HornersRule.html
result += delta
}
if negative {
result *= -1
}
return result
}
}
extension Int {
var asString: String {
guard self != 0 else {
return "0"
}
var chars: [Character] = []
let base = Array("0").first!.asciiValue
var value = self > 0 ? self : -self // We need to convert negatives to positive
while value != 0 {
let ascii = (value % 10) + base
if let unicodeScalar = UnicodeScalar(ascii) {
let c = Character(unicodeScalar)
chars.append(c)
}
value /= 10
}
if self < 0 {
let neg = Character("-")
chars.append(neg)
}
// reverse buffer
chars.reverse()
let result = String(chars)
return result
}
}
let toTest: [String: Int] = [
"42": 42,
"-42": -42,
"1": 1,
"-1": -1,
"0": 0
]
for (k, v) in toTest {
let asInt = k.asInt
assert(asInt == v)
let asStr = v.asString
assert(asStr == k)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment