Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize 4 CGFloats at once

I am trying to use the getRed(green:blue:alpha:) function on UIColor in Swift. For this, I need 4 CGFloat variables (r,g,b,a). Currently, for this, I need to type this code:

var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0

Is there a simpler way to write this, possibly more concise?

like image 303
erdekhayser Avatar asked Sep 14 '14 15:09

erdekhayser


2 Answers

Yes you can use a tuple to declare and initialize them:

var (a: CGFloat, r: CGFloat, g: CGFloat, b: CGFloat) = (0, 0, 0, 0)
like image 143
Antonio Avatar answered Oct 05 '22 21:10

Antonio


Personally, I'm not sure there's a way of declaring those that's any clearer than your original, or that's involves typing that much less. The currently accepted answer is only nine characters shorter, if I've counted them right...

If it's just typing you're worried about, you could use Xcode's built in code snippet library. It allows you to add custom snippets, and assign autocomplete shortcuts.

For this case I'd add your code as a completion snippet, by selecting it in the editor and dragging it to the Code Snippet library (bottom right of the sidebar; go straight to it with View->Utilities->Show Code Snippet Library from Xcode's main menu.) Then I'd probably assign a completion shortcut like "rgba" or something.

Now you're down to typing just a few characters, and you've not used any software outside Xcode to achieve it. Trigger code completion, type "rgba", hit return, and you're done.

Xcode snippet settings

like image 34
Matt Gibson Avatar answered Oct 05 '22 22:10

Matt Gibson