'variable passed by reference before being initialized

I am trying to make a random number generator in swift using 2 user inputs (which are integers) given from the user. I am having a problem generating the number using the function I made with parameters. I get an error stating that both the result1 and result2 variables are being passed by reference before being initialized in the calling to the generate function. EDIT: Gave more info about error

 // Here is the full code. 



 func generate(min: inout Int, max: inout Int) -> Int{
  let finalValue=Int.random(in: min...max)
    return finalValue
}
print("I am gonna assume this works right.")
print("Pick a number (or 2 but please 1 for now)")

var result1: Int
if let input = readLine() {
    if let number = Int(input) {
        result1 = number
    }
}
var result2: Int
if let input = readLine() {
    if let number = Int(input) {
        result2 = number
    }
}

generate(min: &result1, max: &result2)


Solution 1:[1]

You can't guarantee that result1 and result2 have been initialised when you call generate(min: max:) as they are set within if statements. One way around this would be to make them optional, test for that, and bail if still nil.

func generate(min: Int?, max: Int?) -> Int? {
   guard let min = min, let max = max else {return nil}
      return Int.random(in: min...max)
   }
   
var input1, input2: Int?
   
   
if let input = readLine(), let number = Int(input) {
   input1 = number
   
}

if let input = readLine(), let number = Int(input) {
   input2 = number
}


generate(min: input1, max: input2)

There are probably better ways of approaching, but this sticks with your original post.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 flanker