3

I've currently got a string array and I want to convert this to a UInt8 array? All of the strings are UInt8's, however I can only retrieve it as a string. Any ideas?

let stringValues = "[185, 221, 199, 111, 152, 137, 41, 137, 223, 66, 75, 132]"

I have each item in the array split up into its individual part, I just don't know how to convert the string to UInt8.

Thanks

Jay
  • 265
  • 2
  • 10

3 Answers3

1

This works:

var stringValues = "[185, 221, 199, 111, 152, 137, 41, 137, 223, 66, 75, 132]"

stringValues = stringValues.stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "").stringByReplacingOccurrencesOfString(" ", withString: "")

var values = [UInt8]()
print(stringValues)
for item in stringValues.componentsSeparatedByString(",") {
    if let value = UInt8(item) {
        values.append(value)
    }
}
totiDev
  • 5,189
  • 3
  • 30
  • 30
1
let stringValues = "[185, 221, 199, 111, 152, 137, 41, 137, 223, 66, 75, 132]"
let uint8Values = stringValues.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString:" ,\"[]"))
    .filter { !$0.isEmpty}.flatMap{ UInt8($0) }
user3441734
  • 16,722
  • 2
  • 40
  • 59
0

Try this one

For single String conversion to UInt8

let unt = UInt8("231")

or you can use complete array as array of UInt8.

let stringValues :[UInt8] = [185, 221, 199, 111, 152, 137, 41, 137, 223, 66, 75, 132]

deoKasuhal
  • 2,867
  • 20
  • 27