1, the decimal string into the digital swift, if you want to convert the string to a numeric type (such as Integer, floating point type, etc.). You can turn it into a nsstring type first, then turn it back.
|
// Convert the value in the text box to a number var i = (tf1.text as NSString) .intValue var f = (tf1.text as NSString) .floatValue var d = (tf1.text as NSString) .doubleValue |
2, the hexadecimal string is converted to a number (1) to define a conversion method
|
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 starts at 48 if i> = 65 {// A-Z starts at 65, but has an initial value of 10, so it should be minus 55 sum-= 7 } } return sum } |
Use the sample:
|
let str ="FF0000"
let value = hexStringToInt(from:str)
print(value)
|
(2) can also be implemented by extending the string
|
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 starts at 48 if i> = 65 {// A-Z starts at 65, but has an initial value of 10, so it should be minus 55 sum-= 7 } } return sum } } |
Use the sample:
|
let str ="FF0000"
let value = str.hexStringToInt()
print(value)
|
Original from: www.hangge.com reprint please keep the original link: http://www.hangge.com/blog/cache/detail_698.html
Swift-Converts a number of type string to a numeric type (supports decimal, hexadecimal)