Advertisement
HXXXXJ

Is Valid Number

Feb 22nd, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.74 KB | None | 0 0
  1. //no exponent
  2. //6.  or .4 are valid
  3. // only + or - are not valid
  4. // +. are not valid
  5. import Foundation
  6.  
  7. func validDouble(_ s:String) -> Bool{
  8.     guard s.count > 0 else { return false }
  9.     let arr = Array(s.trimmingCharacters(in: .whitespaces))
  10.    
  11.     var foundDot = false
  12.     var i = 0
  13.     var hasValue = false
  14.     while i < arr.count {
  15.         let char = arr[i]
  16.         if i == 0 && (char == "+" || char == "-"){
  17.             i += 1
  18.             continue
  19.         }
  20.         if char == "." {
  21.             if foundDot { return false}
  22.             foundDot = true
  23.             i += 1
  24.             continue
  25.         }
  26.         if char < "0" || char > "9" { return false}
  27.         hasValue = true
  28.         i += 1
  29.     }
  30.     return hasValue
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement