在 Swift 4 中解包可选

Unwrapping an optional in Swift 4

我在 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)

行 result += element * element 出现以下错误 "Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?" 我不想使用“!”我必须测试 nil 情况。我不确定在哪里(甚至不知道如何诚实)打开可选的。建议?

如果您想从数组中删除 nil 值,您可以压缩映射它:

for (index, element) in (someOptionalInts.compactMap { [=10=] }).enumerated() {

那么,element就不是可选的了。


如果您想要将所有 nil 值视为 0,那么您可以这样做:

if index % 2 != 0 {
    result += (element ?? 0) * (element ?? 0)
}

出现该错误是因为您必须指定在元素为 nil 的情况下要执行的操作

if index % 2 != 0 {
    if let element = element {
        result += element * element
    }
    else {
        // do whatever you want
    }
}

您所要做的就是打开可选的包装:

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

这将忽略 nil 值。

与任何类型的映射相比,它的优势在于您不必额外遍历数组。

我会这样写:

for (index, element) in someOptionalInts.enumerated() {
    guard let element = element, index % 2 == 0 else { continue }
    result += element * element
}
// result == 10

guard 语句意味着我只对 element 不是 nil index 感兴趣甚至。