String / Int Conversions
This file contains 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
//: 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