Home Ask Login Register

Developers Planet

Your answer is one click away!

Sunay February 2016

How to Have More Than One Return from a Function Inside a Subclass in Swift

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.



Chris Slowik February 2016

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/

Post Status

Asked in February 2016
Viewed 2,519 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life