Skip to content

Instantly share code, notes, and snippets.

@yanil3500
Last active June 26, 2019 04:05
Show Gist options
  • Save yanil3500/1117367d45e1509af32d1c38d3540656 to your computer and use it in GitHub Desktop.
Save yanil3500/1117367d45e1509af32d1c38d3540656 to your computer and use it in GitHub Desktop.
[String To Integer]
import Foundation
precedencegroup ExponentiationPrecedence {
associativity: right
higherThan: MultiplicationPrecedence
}
infix operator **: ExponentiationPrecedence
func ** (lhs: Int, rhs: Int) -> Int {
return Int(pow(Float(lhs), Float(rhs)))
}
var sampleString = "3459"
extension String {
func convert() -> Int? {
var result: Int = 0
// building value map
var valueMap = [
"0" as Character: 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9
]
// example: 3459
// 3459 = (3 * 10^3) + 4 * 10^2 + 5 * 10^1 + 9 * 10^0
// value * (10 ** exponent)
for (i, c) in self.enumerated() {
let exponent = self.count - i - 1
if let value = valueMap[c] {
result += value * (10 ** exponent)
} else {
return nil
}
}
return result
}
}
sampleString.convert() // 3459
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment