Swift 为什么循环的嵌套会得到一个空值?

Swift 为什么循环的嵌套会得到一个空值?,swift,Swift,大家好。我正在尝试运行上面的代码。这是我在LeetCode对二和问题的看法。基本上,您给出一个数组和一个“target”,代码返回数字的索引,这些数字相加后等于“target” 到目前为止,这两个示例运行良好,它们分别正确返回[0,1]和[1,5] 然而,在这个例子中,twoSum([3,3],6),我意外地发现了nil错误。有人知道为什么吗 提前感谢。因为test1==test2将不会定义num1或num2,当您强制展开nums.index(of:num1) 请尝试以下方法: twoSum([

大家好。我正在尝试运行上面的代码。这是我在LeetCode对二和问题的看法。基本上,您给出一个数组和一个“target”,代码返回数字的索引,这些数字相加后等于“target”

到目前为止,这两个示例运行良好,它们分别正确返回
[0,1]
[1,5]

然而,在这个例子中,
twoSum([3,3],6)
,我意外地发现了nil错误。有人知道为什么吗


提前感谢。

因为
test1==test2
将不会定义
num1
num2
,当您强制展开
nums.index(of:num1)

请尝试以下方法:

twoSum([2,7,11,15], 9)
twoSum([1,5,2,3,5,10], 15)

您应该使用
enumerated()
来避免强制展开 (我对您的代码做了一些更改):

index(of:x)不返回最初从中获取x的索引。它搜索x并返回等于x的nums的第一个元素的索引


你的数组nums是[3,3]。如果搜索nums[0]=3,则索引(of:3)返回0。如果搜索nums[1],它也是3,则索引(of:3)再次返回0。它不会返回1。索引搜索该数字,但不知道该数字来自何处

对!我认为这个问题最初是以一种糟糕的方式解决的,我更喜欢Aleksandr的方法,而不是感谢有意义的方法。我要试试看。
twoSum([2,7,11,15], 9)
twoSum([1,5,2,3,5,10], 15)
for i in nums {
    for x in nums {
        if (i + x == target && i != x) {
            num1 = x
            num2 = i
        }
    }
}
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
    for (test1, i) in nums.enumerated() {
        for (test2, x) in nums.enumerated() {
            if (i + x == target && test1 != test2) {
                return [test1, test2]
            }
        }
    }
    return [0, 0] // but may be you should return nil in this case
}