Search code examples
swiftoption-typeswift-playgroundoptional-values

Unwrapping an optional in Swift 4


I have the following code in a playground:

// Create an empty array of optional integers
var someOptionalInts = [Int?]()

// Create a function squaredSums3 with one argument, i.e. an Array of optional Ints
func squaredSums3(_ someOptionalInts: Int?...)->Int {
    // Create a variable to store the result
    var result = 0

    // Get both the index and the value (at the index) by enumerating through each element in the someOptionalInts array
    for (index, element) in someOptionalInts.enumerated() {
        // If the index of the array modulo 2 is not equal to 0, then square the element at that index and add to result
        if index % 2 != 0 {
            result += element * element
        }
    }

    // Return the result
    return result
}

// Test the code
squaredSums3(1,2,3,nil)

The line result += element * element is giving the following error "Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?" I do not want to use '!' and I have to test for the nil case. I am not sure where (or even how to be honest) to unwrap the optional. Suggestions?


Solution

  • All you have to do is unwrap the optional:

    if let element = element, index % 2 != 0 {
        result += element * element
    }
    

    This will ignore the nil values.

    The advantage of this over any sort of mapping is that you don't have to traverse the array an extra time.