0

我在操场上有以下代码:

// 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)

行结果 += element * element 给出以下错误“可选类型'Int的值?' 没有打开;你是不是要使用“!” 或者 '?'?” 我不想使用“!” 我必须测试 nil 的情况。我不确定在哪里(甚至如何说实话)打开可选的。建议?

4

4 回答 4

2

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

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

这将忽略 nil 值。

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

于 2018-09-04T13:29:32.510 回答
1

如果你想从数组中省略 nil 值,你可以压缩映射它:

for (index, element) in (someOptionalInts.compactMap { $0 }).enumerated() {

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


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

if index % 2 != 0 {
    result += (element ?? 0) * (element ?? 0)
}
于 2018-09-04T13:18:24.120 回答
0

我会这样写:

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

guard声明意味着我只对element不是nil index是偶数时感兴趣。

于 2018-09-04T14:00:53.493 回答
0

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

if index % 2 != 0 {
    if let element = element {
        result += element * element
    }
    else {
        // do whatever you want
    }
}
于 2018-09-04T13:24:58.600 回答