Last active
August 29, 2015 14:18
-
-
Save mrowles/0efbdf4d4a4a602a2515 to your computer and use it in GitHub Desktop.
ATOI in Swift
This file contains hidden or 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
/* | |
* 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This needs mucho improvementso, quick job