Is there any other way to extract the optional without forcing it?

Viewed 44

I need to extract the optional without "!" inside the function:

func arrayFunc1(array1: [Int]) -> Int? {
    let number1 = array1.first
    let number2 = array1.last
    guard array1.count < 2 else {
        return number1! + number2! // it works with "!" but it doesn't work without it
    }
    return nil
}

print(arrayFunc1(array1: [1, 2]))

can I use any other way? if I remove "!" it says I can't use "Binary operator '+' cannot be applied to two 'Int?' operands"

1 Answers

Whatever you bind with a let number1 = ... in a guard clause is not going to be available inside the else of that guard. Rather, they are only available after the guard statement. So you can't bind number1 and number2 and then return them in the else branch of the same guard statement.

You can go for an if instead, checking the opposite condition of count >= 2:

if array1.count >= 2, let number1 = array1.first, let number2 = array1.last {
    return number1 + number2
} else {
    // if you were planning on using number1 and number2 here, you 
    // should use array1.first and .last instead
    return nil
}

I'm not sure what you are planning on doing in the return nil case, but if you are going to use number1 and number2, you should use array1.first and array2.last. Note that these are of type Int?, just like in your original code. After all, there is the possibility that the array could be empty!

If you want to handle the empty case too, you can do:

guard let number1 = array1.first, let number2 = array1.last else {
    return nil // or whatever else you want to do if the array is empty
}
guard array1.count < 2 else {
    return number1 + number2
}
// I'm guessing you're going to use number1 and number2 somehow,
// and want them to be non nullable Ints?
return nil

But then your function only works with 1-element and 2-element arrays. You might just want to take in two Int parameters, with the second being optional:

func someFunc(int1: Int, int2: Int? = nil) -> Int {
Related