swift - How to handle initial nil value for reduce functions -
i learn , use more functional programming in swift. so, i've been trying various things in playground. don't understand reduce, though. basic textbook examples work, can't head around problem.
i have array of strings called "todoitems". longest string in array. best practice handling initial nil value in such cases? think happens often. thought of writing custom function , use it.
func optionalmax(maxsofar: int?, newelement: int) -> int { if let definitemaxsofar = maxsofar { return max(definitemaxsofar, newelement) } return newelement } // testing - nums array of ints. works. var maxvalueofints = nums.reduce(0) { optionalmax($0, $1) } // error: cannot invoke 'reduce' argument list of type ‘(nil, (_,_)->_)' var longestofstrings = todoitems.reduce(nil) { optionalmax(count($0), count($1)) }
it might swift not automatically infer type of initial value. try making clear explicitly declaring it:
var longestofstrings = todoitems.reduce(nil int?) { optionalmax($0, count($1)) } by way notice not count on $0 (your accumulator) since not string optional int int?
generally avoid confusion reading code later, explicitly label accumulator a , element coming in serie x:
var longestofstrings = todoitems.reduce(nil int?) { a, x in optionalmax(a, count(x)) } this way should clearer $0 , $1 in code when accumulator or single element used.
hope helps
Comments
Post a Comment