展开一个可选值时意外找到nil(无法找出哪个部分)

我是Swift的新手,我无法弄清楚我解开了哪个可选变量,并给它分配了nil,我试图在Playground上对其进行调试,但它不允许我单步执行代码。

致命错误:展开一个可选值时意外发现nil

public class ListNode {
    public var val: Int
    public var next: ListNode?
    public init() { self.val = 0; self.next = nil; }
    public init(_ val: Int) { self.val = val; self.next = nil; }
    public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
}
class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        let result = ListNode()
        var resultTail = result
        var carry: Int = 0
        var out: Int = 0
        var val1: Int = 0
        var val2: Int = 0

        var head1: ListNode? = l1
        var head2: ListNode? = l2

        while (l1 != nil || l2 != nil || carry != 0) {

            val1 = head1 != nil ? head1!.val : 0
            val2 = head2 != nil ? head2!.val : 0

            out = (val1 + val2 + carry) % 10
            carry = (val1 + val2 + carry) / 10

            resultTail.next = ListNode(out)
            resultTail = resultTail.next!

            head1 = head1?.next!
            head2 = head2?.next!

        }
        return result.next!
    }
}
let node3 = ListNode(3)
let node2 = ListNode(4, node3)
let node1 = ListNode(2, node2)

let node3a = ListNode(5)
let node2a = ListNode(6, node3a)
let node1a = ListNode(4, node2a)

let solution = Solution().addTwoNumbers(node1, node1a)

最好的祝福, 法罗斯

评论