在Swift 4中展开一个可选项

问题描述 投票:0回答:4

我在操场上有以下代码:

// 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 *元素给出以下错误“可选类型的值'Int?'没打开;你的意思是用'!'要么 '?'?”我不想用'!'我必须测试零案例。我不确定打开可选项的位置(甚至是如何诚实)。建议?

swift optional swift-playground optional-values
4个回答
2
投票

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

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

这将忽略零值。

相对于任何类型的映射,这样做的好处是您不必额外遍历数组。


1
投票

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

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

然后,element将不再是可选的。


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

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

0
投票

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

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

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是偶数时感兴趣。

© www.soinside.com 2019 - 2024. All rights reserved.