【发布时间】:2018-03-08 04:56:04
【问题描述】:
我正在练习 Swift 语言。 我正在用 xcode 中的 Playground 解决 Leetcode 问题。
我对链表中的 assining 和绑定可选值感到困惑。
这是我的代码。
// 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
}
}
var l1 = ListNode(2)
l1.next = ListNode(4)
//first error: here I have an error that editor explains "Value of optional type 'ListNode?' not unwrapped; did you mean to use '!' or '?'?"
l1.next.next = ListNode(3)
//second warning : editors explains that Comparing non-optional value of type 'ListNode' to nil always returns true
while l1 != nil{
print(l1.val)
if let nextNode = l1.next{
l1 = nextNode
}
}
对于第一个错误,如果我输入 !对于展开,它仍然显示错误。
l1.next!.next! = ListNode(3) 或 l1.next.next! = ListNode(3)
我认为我可以展开,因为我确信我为第二个节点放置了正确的节点。
我也试过了
var l1 = ListNode(2)
l1.next? = ListNode(4)
l1.next!.next? = ListNode(3)
那么我会得到
执行被中断,原因:EXC_BAD_INSTRUCTION (代码=EXC_I386_INVOP,子代码=0x0)。
请让我理解可选表达式的正确使用。
【问题讨论】:
-
你需要在init函数中为“next”赋值
-
我认为下一个将是具有 nil 值的 init。不是吗?
-
@UdayBabariya 这不是原因
标签: swift linked-list optional