How to handle initial nil value to reduce functions

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
}   

// Just testing - nums is an array of Ints. Works.
var maxValueOfInts = nums.reduce(0) { optionalMax($0, $1) }   

// ERROR: cannot invoke 'reduce' with an argument list of type ‘(nil, (_,_)->_)'
var longestOfStrings = toDoItems.reduce(nil) { optionalMax(count($0), count($1)) }
+4
source share
3 answers

, Swift . :

var longestOfStrings = toDoItems.reduce(nil as Int?) { optionalMax($0, count($1)) }

, , $0 ( ), String, Int Int?

, , , a , x:

var longestOfStrings = toDoItems.reduce(nil as Int?) { a, x in optionalMax(a, count(x)) }

, $0 $1 .

,

+3

"", nil. , .

+1

, , , :

toDoItems.reduce("") {count ($ 0) > count ($ 1)? $0: $1}

, nil,

toDoItems.reduce(nil as String?) {count ($ 0!) > count ($ 1)? $0: $1}

, , , , $0.

+1

All Articles