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")
In the comparison, you are comparing an optional (
element2
) with an non-optional (element1
).There is no problem comparing an optional to an non-optional. Why should there be? If
element2
isnil
, then the result of the above comparison will betrue
. 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.