6

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!

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Brejuro
  • 3,421
  • 8
  • 34
  • 61

6 Answers6

9

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

CodaFi
  • 43,043
  • 8
  • 107
  • 153
5

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()
ACengiz
  • 1,285
  • 17
  • 23
4

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
Michele Dall'Agata
  • 1,474
  • 2
  • 15
  • 25
0

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

something like:

var chr: [Character] = ["C", "B", "A"]

for a in String(chr[1]).unicodeScalars {
    println(a.value)}
0

For me worked something like:

"\(container[3])".toInt()
Jaro
  • 860
  • 9
  • 21
-1

Why not just for loop the array and convert everything to Int?

https://developer.apple.com/Library/mac/documentation/General/Reference/SwiftStandardLibraryReference/index.html

Betkowski
  • 491
  • 1
  • 4
  • 17