0

I have JSON Data with an array of strings. When I decode this data I need to convert strings into ints and then use it for creating UIColors. But when I convert my hexadecimal from string to int it returns me the wrong color. Here the code

struct DrawingElement {
    let colorsForCells: [UIColor]
}

extension DrawingElement: Decodable {
    
    enum CodingKeys: String, CodingKey {
        case colorsForCells = "cells"
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        let rawColors = try container.decode([String].self, forKey: .colorsForCells)
        colorsForCells = rawColors.map {
            
            let value = Int($0)
            let color = uiColorFromHex(rgbValue: value ?? 77)
            return color == .black ? .white : color
            
        }
    }
   
}
func uiColorFromHex(rgbValue: Int) -> UIColor {
    
    let red =   CGFloat((rgbValue & 0xFF0000) >> 16) / 0xFF
    let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 0xFF
    let blue =  CGFloat(rgbValue & 0x0000FF) / 0xFF
    let alpha = CGFloat(1.0)
    
    return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}

Example of my string in Data: "0xe7c79d"

  • 1
    Your first problem is, you can't convert a string value of `"0xe7c79d"` to an `int`, using `Int(_:String)`, it doesn't make sense, by default, it's expecting a decimal value. Lucky for use, they though of that. Instead you need to use `Int(_:String, radix: Int)` (in fact `Int(_:String)` defaults the `radix` to `10`). The problem is, you first need to get rid of the `0x`. For this you could use `String#dropFirst(_:Int)` to drop the first 2 characters, something like `Int("0xe7c79d".dropFirst(2), radix: 16)` – MadProgrammer Jan 31 '22 at 11:50
  • Why do I need to get rid of "0x"? – synecdochenoire Jan 31 '22 at 11:52
  • Because the conversation to `int` won't work with it – MadProgrammer Jan 31 '22 at 20:36

1 Answers1

1

You have to remove the 0x prefix and then specify the radix 16:

let s = "0xe7c79d"
print(Int(s)) // nil

let value = s.hasPrefix("0x")
    ? String(s.dropFirst(2))
    : s
print(Int(value, radix: 16)) // 15189917
Sulthan
  • 128,090
  • 22
  • 218
  • 270