Is it necessary for the compute function in the Hamming Exercise to return an optional int?

Hi everyone,

I’ve been working on the Hamming exercise and noticed that the compute function currently returns an optional Int?, even though the function either throws an error (when the DNA sequences are of different lengths) or returns a valid integer (the Hamming distance).

Here’s the current implementation:

func compute(_ dnaSequence: String, against: String) throws -> Int? {
    // code
}

The Question:

  • Since the function throws an error when the sequences are of different lengths, is there any reason why it should return an Int??
  • Could we simplify the return type to just Int (non-optional), since the error handling already covers invalid input?

I’ve also noticed that most of the community solutions don’t return an optional integer (Int?), and they directly return an Int after checking the input.

What do you think? Is it fine to return a non-optional Int instead of Int?, especially since most solutions do the same?

Additionally, I’ve seen a similar question posted before but haven’t found any answers yet, so I thought I’d ask again. Link to question

Thanks!

1 Like

Makes sense to me. However, I wonder how many existing solutions do properly return an Int? that will break if the requirements are changed.