如何在Swift中创建引用类型?

时间:2019-03-04 07:57:21

标签: swift

这是一个链表问题:

输入:2 -> 4 -> 35 -> 6 -> 4

预期708

因为342 + 465 = 708

让我感到困惑的是:

result = result!.next在函数toList()

result.next是一个类,一个引用类型,但是当我将其设置为result时,它就像一个右值,result的值类型为nil。为什么以及如何解决?

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */
class Solution {
    func toInt(_ l: ListNode?) -> Int {
        var power = 1, result = 0, curr = l
        while curr != nil {
            result += power * curr!.val
            curr = curr!.next
            power *= 10
        }
        // print("\(result)")
        return result
    }
    func toList(_ i: Int) -> ListNode? {
        var result: ListNode? = nil, num = i
        while num != 0 {
            result = ListNode(num % 10)
            result = result!.next
            num /= 10
        }
        return result
    }
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        return toList(toInt(l1) + toInt(l2))
    }
}

1 个答案:

答案 0 :(得分:-1)

尝试一下:

func toList(_ i: Int) -> ListNode? {
        var result: ListNode? = ListNode(i % 10), num = i / 10
        while num != 0 {
            let nextResult = ListNode(num % 10)
            result!.next = nextResult
            result = result!.next
            num /= 10
        }
        return result
    }