Swift-Converts a number of type string to a numeric type (supports decimal, hexadecimal)

Source: Internet
Author: User


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)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.