https://www.cnblogs.com/Free-Thinker/p/7243683.html
1,十进制的字符串转成数字
Swift中,如果要把字符串转换成数字类型(比如整型,浮点型等)。可以先转成NSString类型,让后再转。
1
2
3
4
|
var i = (tf1.text as NSString ).intValue
var f = (tf1.text as NSString ).floatValue
var d = (tf1.text as NSString ).doubleValue
|
2,十六进制的字符串转成数字
(1)定义一个转换方法
1
2
3
4
5
6
7
8
9
10
11
|
func hexStringToInt(from: String ) -> Int {
let str = from.uppercased()
var sum = 0
for i in str.utf8 {
sum = sum * 16 + Int (i) - 48
if i >= 65 {
sum -= 7
}
}
return sum
}
|
使用样例:
1
2
3
|
let str = "FF0000"
let value = hexStringToInt(from:str)
print (value)
|
(2)也可以通过扩展String实现
1
2
3
4
5
6
7
8
9
10
11
12
13
|
extension String {
func hexStringToInt() -> Int {
let str = self .uppercased()
var sum = 0
for i in str.utf8 {
sum = sum * 16 + Int (i) - 48
if i >= 65 {
sum -= 7
}
}
return sum
}
}
|
使用样例:
1
2
3
|
let str = "FF0000"
let value = str.hexStringToInt()
print (value)
|
|
请发表评论