0

So, I have this function inside a subclass:

func colorAt(x x: Int, y: Int)->UIColor {

        assert(0<=x && x<width)
        assert(0<=y && y<height)

        let uncastedData = CGBitmapContextGetData(context)
        let data = UnsafePointer<UInt8>(uncastedData)

        let offset = 4 * (y * width + x)

        let alpha: UInt8 = data[offset]
        let red: UInt8 = data[offset+1]
        let green: UInt8 = data[offset+2]
        let blue: UInt8 = data[offset+3]

        let color = UIColor(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha)/255.0)

        return color
    }

But, instead of returning a UIColor, I want to return red, green, blue, and alpha individually (so that I don't have to get rgb values from the UIColor later). Is it possible to have more than one return from the function, and if so, how? By the way, not sure if this matters at all, but I also want to be able to access these returns from outside the subclass later on in my code.

Thanks!

Sunay
  • 83
  • 1
  • 5
  • Checkout a tuple, https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Types.html, or you can return a dictionary. If you want to access this outside of this class you can b/c you didn't use the private keyword when defining the function. – Fred Faust Feb 09 '16 at 00:48
  • @sunay http://stackoverflow.com/a/28532880/2303865 – Leo Dabus Feb 09 '16 at 01:01

1 Answers1

0

You could return a tuple.

func colorAt(x x: Int, y: Int) -> (CGFloat, CGFloat, CGFloat) {
    // some stuff to make red, green, and blue vars
    return (redVar, greenVar, blueVar)
}

The Apple docs are pretty good regarding tuples, but here's another source for ya in case you like to read a lot: http://www.codingexplorer.com/tuples-in-swift-create-read-and-return/

Chris Slowik
  • 2,859
  • 1
  • 14
  • 27
  • Oh, right, didn't think of that. Do you think an array would work as well? I've never worked with tuples before. – Sunay Feb 09 '16 at 05:20