在swift中的Stack实现中包含方法

时间:2018-03-20 18:38:49

标签: swift data-structures stack

这是我在网上找到的堆栈实现

public struct Stack<T> {
  fileprivate var array = [T]()

  public var isEmpty: Bool {
    return array.isEmpty
  }

  public var count: Int {
    return array.count
  }

  public mutating func push(_ element: T) {
    array.append(element)
  }

  public mutating func pop() -> T? {
    return array.popLast()
  }

  public var top: T? {
    return array.last
  }
}

我想要一个简单的contains方法来查看元素是否在堆栈中

2 个答案:

答案 0 :(得分:0)

您必须将元素标记为 $loanStartDateRequested = '03/26/2018'; $loanEndDateRequested = '03/26/2018'; foreach($records as $record) { $existingLoanDateRanges = $record->getField('loanDateRanges'); // this returns the comma separated values of existing date ranges // would like to test and compare the dates here and set a variable if available/not available } ,以检查元素中是否有元素可用。此处Equatable标记Stack<T : Equatable>通用元素应为T类型。

检查此代码:

Equatable

使用代码:

public struct Stack<T : Equatable>
{
    fileprivate var array : [T] = [T]()

    public var count : Int { return array.count }
    public var isEmpty : Bool {return array.isEmpty }

    public mutating func push(_ element : T) {
        array.append(element)
    }

    public mutating func pop() -> T? {
        return array.popLast()
    }

    public func peek() -> T? {
        return array.last
    }

    public func contains(_ element : T) -> Bool {
        return self.array.contains { (arrayElement) -> Bool in
            return element == arrayElement
        }
    }
}

此处我的元素是// Create a stack and put some elements on it already. var stackOfNames = Stack(array: ["Carl", "Lisa", "Stephanie", "Jeff", "Wade"]) // Add an element to the top of the stack. stackOfNames.push("Mike") print("Is contains : \(stackOfNames.contains("Carl"))") //true 的类型,String已确认输入String。所以它会起作用。

Equatable

如果您使用自定义类型并希望使用Stack,那么您必须为该类实现extension String : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func ==(lhs: String, rhs: String) -> Bool } 协议。

答案 1 :(得分:0)

打开一个游乐场,开始实现你的Swift堆栈!

首先,请将以下内容写入您的游乐场:

  struct Stack {
      fileprivate var array: [String] = []
    }

将对象推入堆栈相对简单。在堆栈中添加以下方法:

// 1
mutating func push(_ element: String) {
  // 2
  array.append(element)
}

弹出堆栈也很简单。在堆栈内添加以下方法,就在push方法下:

// 1
mutating func pop() -> String? {
  // 2
  return array.popLast()
}

窥视堆栈是检查堆栈的顶部元素。这应该相对简单。 Swift数组有一个last属性,它返回它的最后一个元素而不会改变它自己。尝试自己做!

在堆栈中添加以下内容:

func peek() -> String? {
  return array.last
}