Why is total
optional on line return total + 1
?
return first.enumerated().reduce(0) { total, letter in
let index = first.index(first.startIndex, offsetBy: letter.offset)
if first[index] != second[index]{
return total + 1
}
return total
}
Value of optional type 'Int?' must be unwrapped to a value of type'Int' Coalesce using '??' to provide a default when the optional value contains 'nil' Force-unwrap using '!' to abort execution if the optional value contains 'nil'
So this fixes it:
return first.enumerated().reduce(0) { total, letter in
let index = first.index(first.startIndex, offsetBy: letter.offset)
if first[index] != second[index]{
return total! + 1
}
return total
}
If I break it down the change happens on adding let index
....
OK - This returns the total count of first and total is not optional:
return first.reduce(0) { total, letter in
return total + 1
}
OK - This enumerated and total is not optional:
return first.enumerated().reduce(0) { total, letter in
return total + 1
}
ERROR - This gets a compile error that total is optional
return first.enumerated().reduce(0) { total, letter in
let index = first.index(first.startIndex, offsetBy: letter.offset)
return total + 1
}