Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
func larger<T>(_ a: T, _ b: T) -> T {
a > b ? a : b
}
print(larger(7, 3))It does not compile
- Expecting
7because the call passesInt, which can be compared. The body is checked for anyT, so it needs<T: Comparable>. - Expecting the check to happen during the run, when
Tis known. The compiler rejects the function before the program starts, so nothing runs.
- How would you change the declaration so that the program prints
7? - What error does
larger(Point(x: 1), Point(x: 2))give once the constraint is added?