swift - 在 Swift 4 中展开可选项

标签 swift option-type swift-playground optional-values

我在 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 行给出以下错误“可选类型‘Int 的值?’未展开;您是否打算使用“!”或者 '?'?”我不想使用 '!'我必须测试 nil 情况。我不确定在哪里(甚至不知道如何诚实)打开可选的。有什么建议吗?

最佳答案

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

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

这将忽略 nil 值。

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

关于swift - 在 Swift 4 中展开可选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52167250/

相关文章:

swift - 准确计算 Double

ios - 定义本地 HTML 文件的位置

java - 短路 JavaOptional.flatMap()

haskell - 为什么强制执行 Maybe monad?

swift - 如何在 Xcode 9 Playground 中使用 Swift 包管理器

swift-playground - CIConstantColorGenerator CIFilter 在 Playground 中使用 Swift 2.0 失败并出现错误

swift - AlamofireObjectMapper : JSON with Identifier

swift - 我更新 Xcode 11 和 iOS 13 后,firebase 文本检测不起作用

javascript - 从javascript中的可选设置中读取可选属性

arrays - 如何在 ZStack SwiftUI 中将文本放置在图像的精确位置上