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?
Yes you can use a tuple to declare and initialize them:
var (a: CGFloat, r: CGFloat, g: CGFloat, b: CGFloat) = (0, 0, 0, 0)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With