https://www.cnblogs.com/Free-Thinker/p/7243683.html
1, the decimal character string into digital
Swift, if you want to convert the string into a number types (such as integer, floating point, etc.). You can first turn to NSString type, make and then turned.
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, hexadecimal string into digital
(1) defines a conversion method
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
// 0-9 从48开始
if
i >= 65 {
// A-Z 从65开始,但有初始值10,所以应该是减去55
sum -= 7
}
}
return
sum
}
|
Sample use:
1
2
3
|
let
str =
"FF0000"
let
value = hexStringToInt(from:str)
print
(value)
|
(2) can also be achieved by extending 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
// 0-9 从48开始
if
i >= 65 {
// A-Z 从65开始,但有初始值10,所以应该是减去55
sum -= 7
}
}
return
sum
}
}
|
Sample use:
1
2
3
|
let
str =
"FF0000"
let
value = str.hexStringToInt()
print
(value)
|