-1

I am trying to write a function that takes the sum of 2 variables but I want to be able to make it so I asks the value of the 2 variables instead of manually writing them.

Here is the function I originally wrote:

func sumOfNumbers() {
    var x = 2
    var y = 13

    let sumNumbers = x + y
    print(sumNumbers)
}
sumOfNumbers()

I want it to prompt me in the console for a value of "x" and "y". Thank you.

Aezharhu
  • 9
  • 2
  • Do you want to [read line from console](https://developer.apple.com/documentation/swift/1641199-readline)? – user28434'mstep Dec 04 '18 at 14:30
  • Possibly helpful: https://stackoverflow.com/questions/52794640/allow-line-editing-when-reading-input-from-the-command-line – Martin R Dec 04 '18 at 14:32
  • Or you can do this way : `func sumOfNumbers(x:Int, y:Int) { let sumNumbers = x + y print(sumNumbers) } sumOfNumbers(x:1, y:2)` – canister_exister Dec 04 '18 at 14:37
  • @canister_exister Thank you for the suggestion but that doesn't answer my problem which is that I do not want to set fixed values for __x__ and __y__ but rather have the program prompt me to choose values for them and then it executes the function. – Aezharhu Dec 04 '18 at 14:52
  • `func sumOfNumbers(x:Int, y:Int) { let sumNumbers = x + y print(sumNumbers) }` There is no fixed values, x and y is not set – canister_exister Dec 04 '18 at 14:54
  • Does this answer your question? [Input from the keyboard in command line application](https://stackoverflow.com/questions/24004776/input-from-the-keyboard-in-command-line-application) – pkamb Apr 04 '23 at 16:56

2 Answers2

0

The following code reads multiple inputs and also checks if any of the input is repeated, but it can be used if you are creating a command line tool

while let input = readLine() {
    guard input != "quit" else {
        break
    }

    if !inputArray.contains(input) {
        inputArray.append(input)
        print("You entered: \(input)")
    } else {
        print("Negative. \"\(input)\" already exits")
    }

    print()
    print("Enter a word:")
}
0

Don't get confused if you want to get user input from console. Just write one line of code in your program and rest of thing leave rest in peace.

var getUserInput = Int(readLine()!)!

Done.

HangarRash
  • 7,314
  • 5
  • 5
  • 32