【发布时间】:2018-09-04 13:16:08
【问题描述】:
我在操场上有以下代码:
// 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 的情况。我不确定在哪里(甚至如何说实话)打开可选的。有什么建议吗?
【问题讨论】:
-
做一个
if let:if let unwrappedElement = element { if index %2... {} }?这是基本的展开。或者你可以解开已经someOptionalInts而不是someOptionalInts,而是使用let unwrappedSomeInts = someOptionalInts.flatMap{ $0 }并将其用于循环。 -
result = (element ?? 0) * (element ?? 0)
标签: swift optional swift-playground optional-values