Search code examples
swiftuiimageviewuicolor

Ambiguous reference to member 'subscript'


I get this error: "Ambiguous reference to member 'subscript'" when I try to change color:

struct color {
    var r : Float
    var g : Float
    var b : Float
}

func setPixels(image:[color], pixel: Int) {
    let alpha: Float = 1.0
    let pixelView = view.viewWithTag(pixel) as! UIImageView
    pixelView.backgroundColor = UIColor(
        red: image[pixel].r, //Error: Ambiguous reference to member 'subscript'
        green: image[pixel].g,
        blue: image[pixel].b,
        alpha: alpha)
}

Solution

  • Float it is not the same as CGFloat. You have to pass a CGFloat to the UIColor. Note: You should name your structs starting with a capital letter.

    struct Color {
        let r: CGFloat
        let g: CGFloat
        let b: CGFloat
    }
    
    class ViewController: UIViewController{
        func setPixels(image: [Color], pixel: Int) {
            let alpha: CGFloat = 1
            let pixelView = view.viewWithTag(pixel) as! UIImageView
            pixelView.backgroundColor = UIColor(
                red: image[pixel].r,
                green: image[pixel].g,
                blue: image[pixel].b,
                alpha: alpha
            )
        }
    }