M Gage Morgan M Gage Morgan - 4 months ago 117
Swift Question

How to convert Swift 3 output of readLine() to Integer?

Please don't mark as duplicate until you read the whole thing. This is specific to Swift 3.

I have functions that have parameters such as Ints, Floats, etc. I'd like to take the output of readLine() and have Swift accept the output of readLine() as these types, but unfortunately readLine() outputs a String? and when I try to convert it tells me it's not unwrapped. I need help. I'm using Ubuntu 16.04.

For example, if I had

area(width: 15, height: 15)
, how would I replace 15 and 15 with two constants containing readLine() or any equivalent to readLine() to accept input from a user in the terminal?

Also note that the program I am writing is specifically doing math, as most people seem to be happy with strings, this is literally a CLI-based calculator.

EDIT 1 (lol) Okay, here's a more exact explanation of above. The following code will print the area of a trapezoid:

import Foundation

func areaTrapezoid(height: Float, baseOne: Float, baseTwo: Float) {
let inside = baseOne + baseTwo
let outside = 0.5 * height
let result = outside * inside
print("Area of Trapezoid is \(result)")
}

areaTrapezoid(height: 10, baseOne: 2, baseTwo: 3)


So, the trapezoid has a height of 10 units, and two bases that have lengths of 2 and 3 respectively. However, I want to do something like:

import Foundation

func areaTrapezoid(height: Float, baseOne: Float, baseTwo: Float) {
let inside = baseOne + baseTwo
let outside = 0.5 * height
let result = outside * inside
print("Area of Trapezoid is \(result)")
}

let h = readLine()
areaTrapezoid(height: h, baseOne: 2, baseTwo: 3)


Except, as is already obvious, readLine() will output an optional string, and not a Float. I want the user to be able to input the numbers via CLI in sort of an interactive way, if you will. I'm just learning Swift, but I did something similar in C++ when I was learning that language. Thanks for any help you can provide.

Answer

readLine() returns an Optional String.

To unwrap the String, you can use if let, and to convert the String to an integer, use Int().

Example:

import Foundation
if let typed = readLine() {
  if let num = Int(typed) {
      print(num)
  }
}

Let's say you prompted the user twice:

let prompt1 = readLine()
let prompt2 = readLine()

Then:

if let response1 = prompt1, 
    response2 = prompt2, 
    num1 = Int(response1), 
    num2 = Int(response2) {
    print("The sum of \(num1) and \(num2) is \(num1 + num2)")
}
Comments