這是我必須在 Swift 中使用自定義串列的簡單代碼
public class Node<Value> {
public var value: Value
public var next: Node?
public init(value: Value, next: Node? = nil) {
self.value = value
self.next = next
}
}
extension Node: CustomStringConvertible {
public var description: String {
guard let next = next else {
return "\(value)"
}
return "\(value) -> " String(describing: next) " "
}
}
func creating_and_linking_nodes()
{
let node1 = Node(value: 1)
let node2 = Node(value: 2)
let node3 = Node(value: 3)
node1.next = node2
node2.next = node3
print(node1)
}
我看到以下輸出“1 -> 2 -> 3”,這對我來說有點出乎意料。為什么要遍歷串列print?這是默認行為嗎?有沒有辦法覆寫它并只列印 1 個節點?
uj5u.com熱心網友回復:
public var description: String {
guard let next = next else {
return "\(value)"
}
return "\(value) -> " String(describing: next) " "
}
}
您的代碼以遍歷串列的方式撰寫。所以相應地改變它。這是一個基本錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/444103.html
標籤:迅速
