I would like to learn and use more functional programming in Swift. So, I tried to distinguish things on the playground. However, I do not understand Abbreviations. Basic sample tutorials work, but I cannot solve this problem.
I have an array of strings called "toDoItems". I would like to get the longest string in this array. What is the best practice for handling the initial nil value in such cases? I think this probably happens often. I was thinking of writing a custom function and using it.
func optionalMax(maxSofar: Int?, newElement: Int) -> Int {
if let definiteMaxSofar = maxSofar {
return max(definiteMaxSofar, newElement)
}
return newElement
}
var maxValueOfInts = nums.reduce(0) { optionalMax($0, $1) }
var longestOfStrings = toDoItems.reduce(nil) { optionalMax(count($0), count($1)) }
source
share