-
Notifications
You must be signed in to change notification settings - Fork 5
/
isNumber.swift
72 lines (68 loc) · 2 KB
/
isNumber.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
enum NumberSign {
case positive
case negative
}
func isNumber(_ s: String) -> Bool {
var numbers: [Int] = []
var sign: NumberSign? = nil
var exponents: [Int]? = nil
var exponentSign: NumberSign? = nil
var decimalPointPosition: Int? = nil
var trimmedString = s.trimmingCharacters(in: .whitespacesAndNewlines)
for (index,character) in trimmedString.enumerated() {
switch character {
case "+":
if exponents == nil {
if(index == 0 && sign == nil){
sign = .positive
}else{
return false
}
} else {
if(exponents?.count == 0 && exponentSign == nil){
exponentSign == .positive
}else{
return false
}
}
case "-":
if exponents == nil {
if(index == 0 && sign == nil){
sign = .negative
}else{
return false
}
} else {
if(exponents?.count == 0 && exponentSign == nil){
exponentSign == .negative
}else{
return false
}
}
case "e":
if exponents != nil {
return false
}else{
exponents = []
}
case ".":
if decimalPointPosition != nil || exponents != nil {
return false
}else{
decimalPointPosition = index
}
case "0","1","2","3","4","5","6","7","8","9":
let value = Int(String(character))!
if exponents == nil {
numbers.append(value)
}else{
exponents?.append(value)
}
default:
return false
}
}
if numbers.count == 0 {return false}
if exponents?.count == 0 {return false}
return true
}