Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Character in an array to an Integer

Tags:

xcode

ios

swift

I can't seem to figure out how to do this even though I've searched through documentation.

I'm trying to figure out how to convert a character at an index in an array to an integer.

For example, say I have a character array named "container", I can't figure out how to do:

var number:Integer = container[3]

Thanks for the help!

like image 435
Brejuro Avatar asked Jun 28 '14 05:06

Brejuro


3 Answers

Swift doesn't make it easy to convert 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 pretty close to what you want:

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

For any engineers that come across this question, see rdar://17494834

like image 66
CodaFi Avatar answered Oct 15 '22 05:10

CodaFi


I am not sure that it is effective or not but at least it worked. I converted Character to String then to Int.

String(yourCharacterInArray).toInt()
like image 41
ACengiz Avatar answered Oct 15 '22 03:10

ACengiz


You may try this:

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

It's totally ugly, but it does the job. Also it is a bit computational expensive (O(n) each time one access a character in a string). Still this can be a trick to get back a way to build the 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 implementing a function:

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
like image 29
Michele Dall'Agata Avatar answered Oct 15 '22 05:10

Michele Dall'Agata