I need help programming this very simple function

Hello. I need help programming a project that needs to be able to get several numerical inputs from a user and do several mathematical operations on the input and then print the result.
This has to be done using a function but I get input by doing this:
var answer = readLine()

and then into my function that looks like this:
func SumNumbers (_ numbers:Double...){
var sum: Double = 0
for each in numbers{
sum += each
print("the sum of your numbers is (sum)")

then i try to put the var answer and answer 2 which works the same as answer into it and it says it needs to be a number and not a string

The function readLine() from the swift standard library returns on optional string, which is a different type than a Double. Part of the challenge that I suspect this task is meant to uncover is learning about the type system in swift, and how to convert from one type to another.

The Swift Programming Language is a detailed reference for Swift which covers the topic (the Types section), but there's also more introductory "here's what types are and how they work" in several other places. The "Everyone Can Code" series is really quite good, if you're on a platform that supports Apple's "books" app.

That will lead you to looking at how to convert one type to another, and in this specific case, there are methods on Double (the type) that allow you to create that type from a String, that are probably where you'd want to start looking.

1 Like
Terms of Service

Privacy Policy

Cookie Policy