美文网首页
playground 一个 queueArray 示例

playground 一个 queueArray 示例

作者: _浅墨_ | 来源:发表于2022-03-25 20:17 被阅读0次
    
    public struct QueueArray<T>: Queue {
      
      private var array: [T] = []
      public init() {}
    
      public var isEmpty: Bool {
        array.isEmpty
      }
      
      public var peek: T? {
        array.first
      }
      
      public mutating func enqueue(_ element: T) -> Bool {
        array.append(element)
        return true
      }
      
      public mutating func dequeue() -> T? {
        isEmpty ? nil : array.removeFirst()
      }
    }
    
    extension QueueArray: CustomStringConvertible {
      
      public var description: String {
        String(describing: array)
      }
    }
    
    var queue = QueueArray<String>()
    queue.enqueue("Ray")
    queue.enqueue("Brian")
    queue.enqueue("Eric")
    queue
    queue.dequeue()
    queue
    queue.peek
    
    练习题
    Whose turn is it?

    Imagine that you are playing a game of Monopoly with your friends. The problem is that everyone always forget whose turn it is! Create a Monopoly organizer that always tells you whose turn it is. Below is a protocol that you can conform to:

    public protocol BoardGameManager {
        
      associatedtype Player
      mutating func nextPlayer() -> Player?
    }
    
    extension QueueArray: BoardGameManager {
        
      public typealias Player = T
      
      public mutating func nextPlayer() -> T? {
        guard let person = dequeue() else {
          return nil
        }
        enqueue(person)
        return person
      }
    }
    
    var queue = QueueArray<String>()
    queue.enqueue("Vincent")
    queue.enqueue("Remel")
    queue.enqueue("Lukiih")
    queue.enqueue("Allison")
    print(queue)
    
    print("===== boardgame =======")
    queue.nextPlayer()
    print(queue)
    queue.nextPlayer()
    print(queue)
    queue.nextPlayer()
    print(queue)
    queue.nextPlayer()
    print(queue)
    

    相关文章

      网友评论

          本文标题:playground 一个 queueArray 示例

          本文链接:https://www.haomeiwen.com/subject/objdjrtx.html