Skip to content

Instantly share code, notes, and snippets.

@mrowles
Last active August 29, 2015 14:18
Show Gist options
  • Save mrowles/0efbdf4d4a4a602a2515 to your computer and use it in GitHub Desktop.
Save mrowles/0efbdf4d4a4a602a2515 to your computer and use it in GitHub Desktop.
ATOI in Swift
/*
* Converts ASCII string to an Int where plausible
* @param {String} str the string passed to atoi
* return {Int?} the converted integer value
*/
func atoi(str: String) -> Int? {
// Trim trailing whitespace
var newStr:String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Get length of string
var newStrLen:Int = count(newStr)
if (newStrLen < 1) {
println("String is empty")
return nil
}
var i:Int = 0
var firstChar:Character = newStr[newStr.startIndex]
var posNegMultiplier:Int = 1
// Cater for negative numbers
if (firstChar == "-") {
posNegMultiplier = -1
i++
}
// Init character array to iterate
var characters:Array<Character> = Array(newStr)
// Init cast variables
var currLetter:String = ""
// Prepare result
var result:String = ""
do {
// Get string version of current character
currLetter = String(characters[i])
// Ensure it is not null
if (!currLetter.isEmpty) {
// Check if number
if (currLetter >= "0" && currLetter <= "9") {
result = "\(result)\(currInt)"
}
}
++i;
} while (i < newStrLen)
// Return nil if no result from passed string
if (result.isEmpty) {
return nil
}
// Check for integer overflow
var resultAsDouble:Double = Double((NSString(string: result).doubleValue * Double(posNegMultiplier)))
if (resultAsDouble > Double(Int.max) || resultAsDouble < Double(Int.min)) {
println("Error: Integer too large")
return nil
}
// Pass the result back with multiplier
return result.toInt()! * posNegMultiplier
}
@mrowles
Copy link
Author

mrowles commented Apr 9, 2015

This needs mucho improvementso, quick job

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment