You have to mark your element as Equatable
to check whether element available in array or not. Here Stack<T : Equatable>
mark T
generic element should be of type Equatable
.
Check this code :
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
}
}
}
Use of code :
// 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
Here my element is type of String
, and String
already confirming to type Equatable
. So it will work.
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
}
If you using your custom type and want to make use of Stack then you have to implement Equatable
protocol for that class.