Problem overview
The first challenge is small on purpose, because it teaches how every challenge is built. You get two numbers, a and b, and the method sum must return their sum. For a = 4 and b = 9 the answer is 13.
How a challenge is laid out
Each challenge has an input, the values you are given, and an output, the value your code must produce. The statement describes both and gives examples to check that you understood.
The editor shows this starting code:
class Solution {
func sum(_ a: Int, _ b: Int) -> Int {
}
}
- The class.
class Solutionis a container for the method. Leave it as it is; classes come later in the course. - The method. A method is a function that lives inside a class. You write the solution in its body, between the curly braces.
- The parameters.
aandbare the input. Their names match the statement, and each is anInt, a whole number. - The return type.
-> Intsays the method gives back anInt. This is the output the tests look at.
The underscores before a and b mean that a call doesn't write argument labels: it is sum(4, 9), not sum(a: 4, b: 9).
Approach
There is nothing to search for or loop over. The output is the input values added together. Swift adds two Int values with the + operator, so the whole job is to compute a + b and give it back.
Step by step
- Add the parameters. The expression
a + buses the two inputs directly. There is no need for a new variable. - Return the result. The keyword
returnhands the value back to whoever calledsumand ends the method. Since the header promises anInt, a method with an empty body doesn't compile, and the lesson's tests can only see something that is returned.
The solution in Swift
class Solution {
func sum(_ a: Int, _ b: Int) -> Int {
return a + b
}
}
Swift details worth knowing:
- Returning is not printing. The method produces a value for its caller. Nothing appears on screen unless someone prints that value, as in
print(Solution().sum(4, 9)), which prints13. - Single-expression shortcut. When a function body is one expression, Swift lets you drop the
returnkeyword:a + balone works. Writingreturnis clearer while you are learning. - No semicolons. A statement ends at the end of the line.
- Same types only. Swift doesn't mix number types silently. Adding an
Intto aDoubleneeds an explicit conversion, but here both areInt. - Overflow stops the program.
Intis 64 bits. If a sum goes past the largestInt, the program crashes at run time instead of wrapping around.
Edge cases and common mistakes
- Forgetting
return. An empty body or a body with onlya + bon a line among other statements doesn't give back a value. - Printing instead of returning.
print(a + b)shows the number but returns nothing. - Negative numbers and zero. They work the same way:
sum(-3, 3)returns0. - Changing the signature. The tests call
sumwith the name and the types given, so keep them.
Testing
a = 4,b = 9gives13.a = -3,b = 3gives0.
