I've been familiar with callback functions for many years. But Swift's headache inducing syntax was difficult. It took a couple of passes, but I think I'll be able to read and use in-line closures in the future.
Going beyond simple closures, is there a way to coerce Swift into combining closures and enums, collections, etc?
Consider:
// Greyscale methods
func averaging() { <code for rgb manipulation }
func lunimance() { <different method for rgb manipulation> }
func desaturation() { <code> }
...etc...
var greyscaleMethod = luminance // Allow the user to choose a method
image.makeGreyscale( greyscaleMethod )
It would be interesting to be able to treat a collection of similar closures/functions as we would an array of strings.
This sample code seems to work.
let sortDecending = { (n1:String, n2:String) in n1 > n2 }
let sortAscending = { (n1:String, n2:String) in n1 < n2 }
let sortOrders = [sortAscending, sortDecending]
let sortSequences = [
{ (n1:String, n2:String) in n1 > n2 },
{ (n1:String, n2:String) in n1 < n2 },
]
let names = ["john", "paul", "george", "ringo"]
names
.sorted(by: sortAscending)
.forEach {print($0)}
names
.sorted(by: sortDecending)
.forEach {print($0)}
names
.sorted(by: sortSequences[0])
.forEach {print($0)}
But I could not get closure expressions to work in enums.