swift4, общая функция: последовательность (первая: следующая :) проблема - за пределами: index> = endIndex - PullRequest
0 голосов
/ 31 мая 2018

Я изучаю список алгоритмов и структуры данных Рея Вендерлиха

Код в порядке:

let nodes = sequence(first: lhs.node) { $0?.next  }

Код не в порядке:

let nodes = sequence(first: lhs.node, next: { aNode -> Node<Value>? in
      aNode?.next
})// The question is here 

Iхотите узнать, как правильно исправить грамматику Свифта

error

Чтобы управлять LinkedList, проблема здесь:

public struct LinkedList<Value> {

  public var head: Node<Value>?
  public var tail: Node<Value>?

  public init() {}

  public var isEmpty: Bool {
    return head == nil
  }

  public mutating func push(_ value: Value) {
    copyNodes()
    head = Node(value: value, next: head)
    if tail == nil {
      tail = head
    }
  }

  public mutating func append(_ value: Value) {
    copyNodes()
    guard !isEmpty else {
      push(value)
      return
    }
    tail!.next = Node(value: value)
    tail = tail!.next
  }

  public func node(at index: Int) -> Node<Value>? {
    var currentNode = head
    var currentIndex = 0
    while currentNode != nil && currentIndex < index {
      currentNode = currentNode!.next
      currentIndex += 1
    }
    return currentNode
  }




  private mutating func copyNodes() {
    guard !isKnownUniquelyReferenced(&head) else {
      return
    }
    guard var oldNode = head else {
      return
    }

    head = Node(value: oldNode.value)
    var newNode = head

    while let nextOldNode = oldNode.next {
      newNode!.next = Node(value: nextOldNode.value)
      newNode = newNode!.next
      oldNode = nextOldNode
    }

    tail = newNode
  }
}

extension LinkedList: CustomStringConvertible {

  public var description: String {
    guard let head = head else {
      return "Empty list"
    }
    return String(describing: head)
  }
}

extension LinkedList: Collection {

  public struct Index: Comparable {

    public var node: Node<Value>?

    static public func ==(lhs: Index, rhs: Index) -> Bool {
      switch (lhs.node, rhs.node) {
      case let (left?, right?):
        return left.next === right.next
      case (nil, nil):
        return true
      default:
        return false
      }
    }

    static public func <(lhs: Index, rhs: Index) -> Bool {
      guard lhs != rhs else {
        return false
      }
     var nodes = sequence(first: lhs.node) { $0?.next }

      nodes = sequence(first: lhs.node, next: { (aNode) -> Node<Value>? in
           aNode?.next
      })// The question is here 
        // I overwrite the code to test it

      return nodes.contains { $0 === rhs.node }
    }
  }

  public var startIndex: Index {
    return Index(node: head)
  }

  public var endIndex: Index {
    return Index(node: tail?.next)
  }

  public func index(after i: Index) -> Index {
    return Index(node: i.node?.next)
  }

  public subscript(position: Index) -> Value {
    return position.node!.value
  }
}

ToИспользуйте код:

example(of: "using collection") {
    var list = LinkedList<Int>()
    for i in 0...9 {
        list.append(i)
    }

    print("Array containing last 3 elements: \(Array(list.suffix(3)))")

}

Структура данных LinkedList

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) + " "
  }
}

Язык языка:

public func example(of description: String, action: () -> Void) {
  print("---Example of \(description)---")
  action()
  print()
}

Я проверил документ Apple, https://developer.apple.com/documentation/swift/2015879-sequence

и не нашли ни одной хорошей идеи.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...