Search code examples
swiftoptional-values

Why does this work (not using vs. using optionals)?


Why does alternative1 below work flawlessly?

The macros are bogus of course and for illustration purposes only:

func commonPrefixLength<T: Swift.Collection, U: Swift.Collection where
    T: Sequence, U: Sequence,
    T.GeneratorType.Element: Equatable,
    T.GeneratorType.Element == U.GeneratorType.Element>
    (collection1: T, collection2: U) -> T.IndexType.DistanceType {
        var collection2generator = collection2.generate()

        var i: T.IndexType.DistanceType = 0

        for element1 in collection1 {
#if alternative1
            let element2 = collection2generator.next()

            if (element1 != element2) {
                return i
            }
#elseif alternative2
            let optionalElement2 = collection2generator.next()

            if let element2 = optionalElement2 {
                if (element1 != element2) {
                    return i
                }
            }
            else {
                break
            }
#endif

            i++
        }

        return i
}
commonPrefixLength("abX", "abc")

Here is a gist of the above.


Solution

  • In the comparison, you are comparing an optional (element2) with an non-optional (element1).

    if (element1 != element2) {
        return i
    }
    

    There is no problem comparing an optional to an non-optional. Why should there be? If element2 is nil, then the result of the above comparison will be true. That's well defined.

    Non-optionals can be implicitly cast to optionals, otherwise you wouldn't be able to assign a non-optional to an optional.

    let nonOptional = ""
    var optional: String? = nonOptional