Convert character to array into integer

I cannot figure out how to do this, even if I was looking for documentation.

I am trying to figure out how to convert a character from an index to an array into an integer.

For example, let's say I have an array of characters named "container", I cannot figure out how to do this:

var number:Integer = container[3] 

Thanks for the help!

+6
source share
6 answers

Swift does not simplify the conversion between primitive and typed representations of things. Here's an extension that should help in the meantime:

 extension Character { func utf8Value() -> UInt8 { for s in String(self).utf8 { return s } return 0 } func utf16Value() -> UInt16 { for s in String(self).utf16 { return s } return 0 } func unicodeValue() -> UInt32 { for s in String(self).unicodeScalars { return s.value } return 0 } } 

This allows you to get closer to what you want:

 let container : Array<Character> = [ "a", "b", "c", "d" ] /// can't call anything here, subscripting also broken let number = container[2] number.unicodeValue() /// Prints "100" 

For any engineers who run into this issue, see rdar: // 17494834

+9
source

I'm not sure if it is effective or not, but at least it worked. I converted the character to String and then to Int.

 String(yourCharacterInArray).toInt() 
+5
source

You can try the following:

 var container = "$0123456789" var number:Int = Array(container.utf8).map { Int($0) }[3] 

It is absolutely ugly, but it does the job. Also, this bit is computationally expensive (O (n) every time one access to a character in a string). However, this may be a trick to return a way to create CStrings:

 typealias CString = Array<CChar> func toCString(string: String) -> CString { return Array(string.utf8).map { CChar($0) } + [0] } var cString = toCString("$ 0123456789") println("The 2nd character in cString has value \(cString[1])") // It outputs 32 

or without function implementation:

 var container = "$ 0123456789" var containerAsCString = Array(container.utf8).map { CChar($0) } + [0] println("The 2nd character in container has value \(containerAsCString[1])") // It outputs 32 
+4
source

Why not just convert the character to String, get unicodeScalars for it, and extract the .value value to a scalar?

sort of:

 var chr: [Character] = ["C", "B", "A"] for a in String(chr[1]).unicodeScalars { println(a.value)} 
0
source

For me it was something like:

 "\(container[3])".toInt() 
0
source

Source: https://habr.com/ru/post/971452/


All Articles