Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift function without argument labels

Let's say I write the following function in Swift 3:

func rgb(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor {
    return UIColor.init(red: r, green: g, blue: b, alpha: 1)
}

When I call it, I must write let black = rgb(r:0, g:0, b:0)

Is it possible to write this function so that I can call it as let black = rgb(0, 0, 0)?

like image 261
Daniel Avatar asked Jul 11 '26 05:07

Daniel


1 Answers

Use an _ to ignore the label:

func rgb(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat) -> UIColor {
    return UIColor(red: r, green: g, blue: b, alpha: 1)
}

Arguments can have two parameter names, an external name followed by the internal name. An underscore (_) means 'ignore this value', so the external label isn't required at the call site.

like image 74
nathangitter Avatar answered Jul 17 '26 21:07

nathangitter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!